How to run HTTPS in development with Nginx and Docker
Literally every time I build anything I seem to forget how to do this, so mainly this is for future me when I without a doubt need to google this again.
Most of the web now requires SSL for basically everything, browsers will shout at you third parties may not accept the http-only
domains (Shopify doesn’t for webhooks). Thats all well and good in production but we build things on our local machines, so how do I get a SSL certificate to work with something like tom.dev
?
Running NGINX as a reverse proxy
The easiest way I have found to do all of this is to use Docker and NGINX as a reverse proxy.
First up create a docker-compose.yml
file with the following setup:
# docker-compose.ymlversion: '3.1'services:
nginx:
image: nginx:latest
ports:
- 80:80
- 443:443
restart: always
volumes:
- ./nginx/conf/:/etc/nginx/conf.d/:ro
- ./nginx/certs:/etc/nginx/ssl
And create a the directories for the volumes:
docker-compose.yml
nginx/
conf/
certs/
If you now run docker compose up
you should have nginx up and running.
Configure your proxy
Next we need to tell Nginx how to route our traffic, this is all controlled with configuration files:
Create a new file with the following content at nginx/conf/tom.conf
# nginx/conf/tom.confserver {
listen 80;
listen [::]:80;server_name tom.dev;location / {
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header Host $http_host;
proxy_pass http://host.docker.internal:5001;
}
}server {
listen 443 ssl http2;
listen [::]:443 ssl http2;server_name tom.dev;ssl_certificate /etc/nginx/ssl/_wildcard.tom.dev.pem;
ssl_certificate_key /etc/nginx/ssl/_wildcard.tom.dev-key.pem;
location / {
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header Host $http_host;
proxy_pass http://host.docker.internal:5001;
}
}
Generate some SSL certificates
Im sure you can do this manually by … eh there is a great tool for this Mkcert.
Install that and then do the following:
cd nginx/certs
mkcert "*.tom.dev"
That will then generate certificates for the tom.dev
domain and any subdomains you add later.
Tell your PC where to go
The final thing you need to do is tell you PC to direct all traffic back to your localhost. Thats done via your hosts file:
vi /etc/hosts127.0.0.1 tom.dev