The best setting for a highly available NGINX container should be something like the following:
$ docker run -d –name nginx –restart unless-stopped \
-p 80:80 –memory 1000M –memory-reservation 250M nginx:1.18.0
Let’s take a look at this in more detail:
- -d: Run as a daemon in detached mode.
- –name nginx: Give the name nginx.
- –restart unless-stopped: Always automatically restart on failures unless explicitly stopped manually, and also start automatically on Docker daemon startup. Other options include no, on_failure, and always.
- -p 80:80: Forward traffic from host port 80 to container port 80. This allows you to expose your container to your host network.
- –memory 1000M: Limit the container memory consumption to 1000M. If the memory exceeds this limit, the container stops and acts according to the –restart flag.
- –memory-reservation 250M: Allocate a soft limit of250M memory to the container if the server runs out of memory.
We will look into other flags in the subsequent sections as we get more hands-on.
Tip
Consider using unless-stopped instead of always as it allows you to stop the container manually if you want to do some maintenance.
Now, let’s list the containers and see what we get:
$ docker ps -a | |||||||
CONTAINER ID | IMAGE | COMMAND | CREATED | STATUS | PORTS | NAMES | |
06fc749371b7 | nginx | “/docker- | 17 | seconds | Up 16 | 0.0.0.0: | nginx |
entrypoint.…” | ago | seconds | 80->80/tcp | ||||
beb5dfd529c9 | nginx: | “/docker- | 22 | minutes | Up 22 | 80/tcp | fervent_shockley |
1.18.0 | entrypoint.…” | ago | minutes |
If you look carefully, you’ll see a container called nginx and a port forward from 0.0.0.0:80 -> 80.
Now, let’s curl on localhost:80 on the host to see what we get:
$ curl localhost:80
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
…
</html>
We get the NGINX welcome message. This means NGINX is running successfully, and we can access it from the machine. If you have exposed your machine’s port 80 to the external world, you can also access this using your browser as follows:
Figure 3.1 – The NGINX welcome page
You also might want to restart or remove your container occasionally. We’ll look at ways to do that in the next section.
Restarting and removing containers
To restart your containers, you must stop them first and then start them.
To stop your container, run the following:
$ docker stop nginx
To start your container, run the following:
$ docker start nginx
If you want to get rid of your container completely, you need to stop your container first and then remove it, using the following command:
$ docker stop nginx && docker rm nginx
Alternatively, you can use the following command to do it in one go:
$ docker rm -f nginx
Now, let’s look at how we can monitor our containers with tools such as journald and Splunk.