Cell internalization of a blastomere, namely gastrulation, is a common and significant milestone during development of metazoans from worm to human, which generates multiple embryonic layers with distinct cell fates and spatial organizations. Although many molecular activities (e.g., cell polarization, asymmetrical intercellular adhesion, and apical actomyosin cortex contraction) have been revealed to facilitate this morphogenetic process, in this paper, we focus on gastrulation of the worm Caenorhabditis elegans and demonstrate that even a simple mechanical system, like a group of cells with isotropic repulsive and attractive interactions, can experience such internalization behavior spontaneously when dividing within a confined space. In principle, when the total cell number exceeds a threshold, a double-layer structure acquires lower potential energy and longer neighbor distance than the single-layer one. Besides, both mechanical analysis and simulation suggest that the cells with a large size or placed near a small-curvature boundary are easier to internalize. Last but not least, extra regulation on a limited part of cells to internalize autonomously can stabilize this process against motional noise. Our work successfully recaptures many key characteristics in worm gastrulation by mechanical modeling and provides a novel and rational interpretation on how this phenomenon emerges and is optimally programed.