I’m following the instructions on Next.js’ documentation to start the server using Docker: https://nextjs.org/docs/deployment#docker-image
Loading the site with http works but https returns SSL protocol errors.
What I did in detail:
-
Configured NGINX and cerbot (note that the guide is for Ubuntu 20) https://certbot.eff.org/instructions?ws=nginx&os=ubuntufocal on my DigitalOcean Ubuntu 22.4 server
-
Copied
Dockerfile
and.dockerignore
from the example project linked in the docs to my project: https://github.com/vercel/next.js/tree/canary/examples/with-docker -
Built and uploaded the image to the server.
-
Started the image on the server:
docker run -p 80:3000 -p 443:3000 my_image
HTTP works perfectly (https://mysite.mydomain
). With HTTPS I get errors, e.g. ERR_SSL_PROTOCOL_ERROR
on Chrome and SSL_ERROR_RX_RECORD_TOO_LONG
on Firefox.
Any ideas?
2
Answers
The following steps explain how to set up a multi-container Docker Compose environment where NGINX is used as a reverse proxy in front of the Next.js application to handle the SSL connection (and offer an HTTPS URI).
Step 1 – Dockerize Next.js application
Luckily, this is part of the Next.js official docs themselves. The key step is to copy this Dockerfile to the Next.js repo you are working on.
Gotchas:
output: 'standalone'
innext.config.js
(like this)Dockerfile
(3000 by default) is not what will be externally exposed; there’s no need to expose that port publiclydocker build -t nextjs:latest -f Dockerfile .
Step 2 – Set up a Docker Compose environment
The Docker Compose environment will have two running containers: the Next.js app and NGINX.
The NGINX image can be created by adding a second
Dockerfile
:Build the image from the project root dir with
docker build -t nginx:latest -f nginx/Dockerfile nginx
.Then, we can create a
docker-compose.yml
file:Gotchas:
nginx.conf
can be added for now, it’ll be configured in the next step/etc/ssl
. An alternative would be to pack them in the NGINX image (e.g. addCOPY my_ssl_cert.crt /etc/nginx/ssl/my_ssl_cert.crt
to theDockerfile
, idem for the key)Step 3 – Configure NGINX as a reverse proxy
Example
nginx.conf
:Gotchas:
nextjs
because by default Compose sets up a single network for your app (docs)Step 4 – Deploy
docker-compose.yml
to the serverdocker compose up
docker logs [container_name]
to debug any issues;curl http://localhost:80
andcurl --insecure https://localhost:443
can also helpThis answer was really useful. For me on Ubuntu 20.4
needs to be
(yes, the dot)
also for some reason docker can only work on directories that are two levels down from the base.. so for example /var/www but not /var/www/html
I have no idea why this isn’t actually documented on the internet (at least not that I could find)