Using Nginx inside a Docker container is a common approach for web applications, especially when paired with the Django framework and Gunicorn. Typically, you have one Docker container for Django and Gunicorn, another for the database, and a final one for Nginx. Nginx acts as a reverse proxy, forwarding requests from the server to Gunicorn. For this setup, Nginx listens for requests by binding the server’s public port to the Nginx container’s port (e.g., 80 for HTTP or 443 for HTTPS). In this guide, we’ll set up Nginx with HTTPS in a Docker environment.
Ensure you have a working Docker Compose configuration. Back up your configuration files and commit any changes to Git for easy rollback if needed. Assume the following file structure:
Posible file tree
├── Dockerfile
├── docker-compose.yaml
├── nginx
│ ├── Dockerfile
│ └── nginx.conf
└── src
Nginx Docker file
|
|
Nginx configuration
|
|
I posted docker compose and main Docker file inside of this gist .
Map the necessary ports in docker-compose.yaml: 80 port for the incomming http traffic and also 443 for the https.
|
|
Add Certbot to your docker-compose.yaml to automatically obtain Let’s Encrypt certificates: Certbot it is an open source software, which automatically provides letsencrypt certificates. Certbot will produce files required for the nginx, thats why we need to have a volumes and inject those volumes to the nginx container.
|
|
Inject these volumes into the Nginx service:
|
|
Full docker compose configuration is here .
Modify your Nginx configuration to transfer all incoming traffic from 80 port (which is default port for the http) to 443 (which is default port for the https). Create a new server block which will listen for the 443 port. Basically we just shifted all the listeners to the new server block.
|
|
Currently configuration is working, but only with the https and to start accepting request from the http we need to add new block.
|
|
Full nginx configuration is here
Run Certbot to obtain the certificates
Don’t forget to build the docker images and make sure that nginx container is up, and you specified right domain name inside of the command bellow.
sudo docker compose run --rm certbot certonly --webroot --webroot-path /var/www/certbot/ --dry-run -d example.org
If there are no errors, remove the –dry-run flag to obtain the actual certificates:
sudo docker compose run --rm certbot certonly --webroot --webroot-path /var/www/certbot/ -d example.org
Remember to renew your certificates every three months:
docker compose run --rm certbot renew
Also if you’re using Django don’t forget to add follwing options in your settings.py
CSRF_TRUSTED_ORIGINS = ['https://domain.site']
CSRF_COOKIE_HTTPONLY = False
It’s done! Your server is oficially working with the https traffic!