Docker exec nginx reload

Problem

You host nginx inside a docker container. And you need to let it read the new config again. Or the new source code because you changed something.

Solution

Execute the command docker exec -it $name bash -c “nginx -s reload”.

The variable $name can represent:

  • the name of the container you set on starting it
  • the name of the container generated from docker-compose on starting
  • the id of the container

Explanation

nginx -s is the command to send a signal to Nginx.

nginx -s reload adds the parameter to start a new worker. And a new worker reads the config and the files from the file system. Without interrupting serving current connection.

This is called hot reload.

It makes sure the old worker finishes serving. To do it it still uses the old, cached config and the cached files. But new connections will all be served by the new worker. And that with the new config and the freshly read source code from the file system.

docker exec -it $name bash -c “nginx -s reload” means execute a command (bash -c “nginx -s reload”) inside the context of a container (specified by $name).

bash -c “nginx -s reload” itself means execute the command “nginx -s reload” through bash (the Bourne Again SHell https://www.gnu.org/software/bash/)

Background

Sometimes you just need to let nginx reload it´s config and/or the files it´s supposed to host. On an installation directly on the host OS it is to do this via a script, which w.g. when you need to do it programmatically on a new code deployment.

Manually it´s also easy to switch into the container and reload the config. Or killing the container itself and starting a new instance, forcing a reload brute force.

But finding the correct command to execute it correctly within a script without restarting the docker container and interrupting service can take you some time.

Let me know when this helped you.

Best,

Frank

Sources:

https://wiki.alpinelinux.org/wiki/Nginx#:~:text=Reload%20and%20Restart%20Nginx,-Changes%20made%20in&text=Reloading%20will%20do%20a%20%22hot,shutdown%20the%20old%20worker%20processes.

Leave a Reply