1. Ecology can have a profound influence on social evolution. However, the role of ecology in the evolution of specialized altruistic phenotypes or 'castes', a recurrent theme in insect societies, is poorly understood. 2. Cephalotes ants nest in pre-existing arboreal cavities, and extant species span four incremental steps in the evolution of a soldier caste that is morphologically specialized for blocking cavity entrances. I address the hypothesis that ecological specialization, defined as specialized use of cavities with entrances close to the area of one ant head, has selected for a morphologically and behaviourally specialized soldier in Cephalotes. This is done with comparative studies of four Cephalotes species, with one representative for each of the four character states of soldier evolution. 3. By quantifying nesting ecology, nest defence and foraging behaviour, I provide strong support for two key predictions of the focal hypothesis. First, the least specialized nesting ecology is seen in the species with the ancestral state of no-soldier. Thus, more individuals are needed to block the average entrance than in other species, and the variation in entrance area is also greater. Second, a systematic increase in ecological specialization (lower mean and variance of entrance area), and behavioural specialization of soldiers, is associated with each of the three transitions to more specialized soldier morphology. This pattern culminates in the consistent use of cavities with an entrance area equal to one soldier head, and a strict soldier-only blocking defence, in the species representing the most specialized and derived soldier morphology. All species used some entrances equal to one ant head, thus it was specifically the specialization on such nests that was associated with increased morphological and behavioural specialization of the soldier. 4. Overall, theses findings provide strong comparative support for the hypothesis that ecological specialization has played a key role in the evolution of a specialized soldier caste in Cephalotes. This pattern is opposite to classic theoretical prediction that a broader resource base should select for caste evolution. The idea that ecological specialization could be a general force in caste evolution is explored, with critical comparative and experimental tests discussed.