Animals locate and track chemoattractive gradients in the environment to find food. With its small nervous system, Caenorhabditis elegans is a good model system in which to understand how the dynamics of neural activity control this search behaviour. Extensive work on the nematode has identified the neurons that are necessary for the different locomotory behaviours underlying chemotaxis through the use of laser ablation, activity recording in immobilized animals and the study of mutants. However, we do not know the neural activity patterns in C. elegans that are sufficient to control its complex chemotactic behaviour. To understand how the activity in its interneurons coordinate different motor programs to lead the animal to food, here we used optogenetics and new optical tools to manipulate neural activity directly in freely moving animals to evoke chemotactic behaviour. By deducing the classes of activity patterns triggered during chemotaxis and exciting individual neurons with these patterns, we identified interneurons that control the essential locomotory programs for this behaviour. Notably, we discovered that controlling the dynamics of activity in just one interneuron pair (AIY) was sufficient to force the animal to locate, turn towards and track virtual light gradients. Two distinct activity patterns triggered in AIY as the animal moved through the gradient controlled reversals and gradual turns to drive chemotactic behaviour. Because AIY neurons are post-synaptic to most chemosensory and thermosensory neurons, it is probable that these activity patterns in AIY have an important role in controlling and coordinating different taxis behaviours of the animal.