Mutualistic networks are formed when the interactions between two classes of species are mutually beneficial. They are important examples of cooperation shaped by evolution. Mutualism between animals and plants has a key role in the organization of ecological communities1, 2, 3. Such networks in ecology have generally evolved a nested architecture4, 5 independent of species composition and latitude6, 7; specialist species, with only few mutualistic links, tend to interact with a proper subset of the many mutualistic partners of any of the generalist species1. Despite sustained efforts5, 8, 9, 10 to explain observed network structure on the basis of community-level stability or persistence, such correlative studies have reached minimal consensus11, 12, 13. Here we show that nested interaction networks could emerge as a consequence of an optimization principle aimed at maximizing the species abundance in mutualistic communities. Using analytical and numerical approaches, we show that because of the mutualistic interactions, an increase in abundance of a given species results in a corresponding increase in the total number of individuals in the community, and also an increase in the nestedness of the interaction matrix. Indeed, the species abundances and the nestedness of the interaction matrix are correlated by a factor that depends on the strength of the mutualistic interactions. Nestedness and the observed spontaneous emergence of generalist and specialist species occur for several dynamical implementations of the variational principle under stationary conditions. Optimized networks, although remaining stable, tend to be less resilient than their counterparts with randomly assigned interactions. In particular, we show analytically that the abundance of the rarest species is linked directly to the resilience of the community. Our work provides a unifying framework for studying the emergent structural and dynamical properties of ecological mutualistic networks2, 5, 10, 14.