You can match speed and fly formation with another aircraft much in the same way that you can match speed and drive in tight proximity to another automobile on the freeway; just a stream of minute and precise inputs to the accelerator, steering wheel and brake pedal. Aircraft have the additional challenge in that they move in three dimensions and their relative motions are much more inertial than an automobile; you cannot simply stop or arrest a relative closure as fast as you can in a car or truck.
Formation flying is an art form rarely practiced outside of the military because it is otherwise superfluous and useless in civilian aviation. Training begins with two ship formations at 75-100 feet apart and gradually reduces to 15 or so feet as the student pilot builds ability and confidence in the maneuver. Advanced formation flying or aerial refueling takes the student within 6-8 ft of another aircraft. By this point, maintaining formation has become second nature but the student still has to refine the precision to the point that he/she can hold on the boom or hook up with the drogue basket.
Formation flying starts with a process of the wingman 'walking up' on the lead with a closing speed which gradually reduces the closer the wingman gets to the lead ship. In general this is about 10kts for ever NM the two ships are separated by. Once the pilot assumes formation, it's a matter of keeping your eyeballs glued on the leader and making minute stick and throttle inputs. It just takes practice but you can get the hang of it within about 10-15 hours of practice formation flying.
There are limits to just how close you can fly next to another aircraft. Precision flying teams such as the USAF Thunderbirds or the USN Blue Angels will never fly closer than a 36 inch separation between aircraft. In addition this minimum spacing grows depending on the complexity and difficulty of the maneuvers which they are flying.