07.06.2023

How to run Nginx in a Docker container on Ubuntu

Why you could want to run nginx in docker

The one of the main docker advantage is total idempotency. Docker image is "thing in itself", you can copy or move it to other server and image's behavior will be the same.

Docker setup

Before run any "containerized" software, you should install docker itself. Let's to it:

curl -fsSL https://get.docker.com -o initial.sh; bash ./initial.sh

Create the directory for the project files:

mkdir -p ~/project/content

Put the content into this directory. I will just create one page for demo-purposes:

echo "<h1>Serverspace is the best hosting company</h1>" > ~/project/content/index.html

Start the service:

docker run --name nginxapp -p 80:80 -v ~/project/content:/usr/share/nginx/html nginx

Server should give you correct answer if you open its IP via web:

It is enough for minimal configuration, but you could "attach" additional config-files to the web-server if needed. Also I advice you run container with -d flag, this flag will "say" docker to run the container into background so you can close terminal session:

docker run --name nginxapp -p 80:80 -v ~/project/content:/usr/share/nginx/html -v ~/project/yourdomain.conf:/etc/project/conf.d/yourdomain.conf -d nginx

Conclusion

In this matherial I said some advantages of containerized nginx running and described way to run it on Ubuntu 20.04.

You may be also interested in