Its origin was during the Raj when we had a British Army in India. There was a sanitorium in the hills at a place called Deolali, and soldiers who became mentally afflicted were sent there. Hence we have gone Doo Lally when we go off our rockers!!
Deolali was a transit camp in India. The explanation given to me from someone whose father was a medical officer in India, is that soldiers who showed (or pretend to have) mental problems ('a touch of the sun') were sent there to await the next ship home. They were said to have Doolally Tap (which is Urdu for fever).