The nearest major railway station for Ooty, is Coimbatore, with long distance train connections.
From Bangalore to Coimbatore there are 5 daily express trains, and also few more weekly long-distance trains pass via Coimbatore.
If you don’t mind catching a connection train in the midnight, aim for the Nilgiri Express ( Train Number 12671) that connects Chennai (MAS) to Metupalayam (Metupalaiyam / MTP). From Bangalore catch a train to Salem Junction (SA). Nilgiri Express arrives at Salem at 1:47AM in the midnight. This train goes all the way to Mettupalayam via Coimbatore. From Mettupalayam you can catch the mountain train ( Nilgiri Mountain Railway ) to Ooty.
The mountain train is in fact a connection train for the Nilgiri Express that brought you to Mettupalayam. It is also possible reserve up to Ooty ( instead of Mettupalayam) when you do the reservation in the Nilgiri Express.
That will ensure you a seat in the other wise limited seat mountain train to Ooty.
Nilgiri Express reaches Coimbatore by 4.50 am, and Mettupalayam by 6.15 am. If you are opting for the mountain train to Ooty, you will reach Ooty by noon. A faster option is to catch a bus from Metupalayam to Ooty. Mettupalayam to Ooty mountain train takes about 5-1/2 hours, while a bus takes just about 2 hours by road.
In short Coimbatore is the nearest main railway station for Ooty. Further you can reach Ooty via Mettupalayam. There are frequent bus connections from Coimbatore to Mettupalayam. And also from Mettupalayam to Ooty.
Alternatively you can travel from Bangalore to Ooty by bus too. There are a good number of bus services from Bangalore to Ooty.