It's a contraction of the phrase 'do off' just as the opposite 'don' is a contraction of 'do on'. They mean the removal or putting on of items of clothing such as caps.
And used poetically by The Two Ronnies in their song, Bold Sir John.
As Bold Sir John walked on afar, He spied a maiden fair;
"I beg you sir don't come too near, For I've seen many a maiden here;
Get lost amongst the new mown hay, So doff your hat I pray".
Get lost! Get lost! Get lost! Get lost! Get lost amongst the new mown hay.
Sod off! Sod off! Sod off! Sod off! So doff your hat I pray.