Like many behaviors, Caenorhabditis elegans egg laying alternates between inactive and active states. To understand how the underlying neural circuit turns the behavior on and off, we optically recorded circuit activity in behaving animals while manipulating circuit function using mutations, optogenetics, and drugs. In the active state, the circuit shows rhythmic activity phased with the body bends of locomotion. The serotonergic HSN command neurons initiate the active state, but accumulation of unlaid eggs also promotes the active state independent of the HSNs. The cholinergic VC motor neurons slow locomotion during egg-laying muscle contraction and egg release. The uv1 neuroendocrine cells mechanically sense passage of eggs through the vulva and release tyramine to inhibit egg laying, in part via the LGC-55 tyramine-gated Cl- channel on the HSNs. Our results identify discrete signals that entrain or detach the circuit from the locomotion central pattern generator to produce active and inactive states.