Massive black holes are found to be ubiquitous in the nuclei of nearby galaxies, and their growth and evolution appear to be closely linked to that of their hosts. "Binary" black holes are also predicted to exist. The paradigm is that massive black holes, hidden in the nuclei of merging galaxies, would pair inside the violently relaxed core of the newly formed systems, and form a binary under the action of gas--dynamical and gravitational torques. Further hardening would bring the binary to such a close orbit (of months to a few light-days across) that gravitational waves would drive the final black hole coalescence, within less than a Hubble time. Through their loud gravitational wave emission, their is the hope to weight black hole masses and spins, but also to witness the cosmic assembly of galaxies. This is the reason why massive black hole coalescence events are considered to be primary target for the planned Laser Interferometer Space Antenna. So far it has not been possible to show that black hole binaries are a natural outcome of galaxy mergers. The sequence and timing of events that lead to the formation of a binary in the nuclei of galaxies is poorly known due to the difficulty of modeling stellar and gas dynamical processes over more than ten orders of magnitude in density. Here we report the first hydrodynamical simulations that show the formation of a massive black hole binary, following a galaxy-galaxy collision. The simulations track the orbital evolution of the black hole pair from the initial stage of the merger between two gas-rich galaxies a hundred thousand light years apart, to a final separation of only a few light years. We show that a few million years after the merger is completed, a binary forms owing to the action of dynamical friction in a thick, turbulent, gaseous nuclear disk. The disk forms as a result of the dramatic gas inflow that ensues during the last stage of the merger, and is heated by a major starburst. We also show that energetic feedback on the surrounding disk, from the two black holes while they are spiraling inward must be negligible, otherwise dynamical friction against such a bloated hot gas would be inefficient and binary formation early aborted. Double AGN activity comes as a natural outcome of a merger and will be discussed in light of our findings.