Daniel Stokes

Easy ssl certificates for docker with letsencrypt

March 31st 2021 8:16pm
Updated: March 31st 2021 8:24pm

Having a ssl certificate is so crucial these days not only for security but because web browsers may prevent you page from being loaded without one. If you're using docker then here is a really simple way of getting ssl setup and with the added bonus of easy subdomain setup.

This is setup using nginx-proxy and the docker-letsencrypt-nginx-proxy-companion

Below you can see an example docker-compose file to set this up.

Dockerfile

	version: "3.7"

services:
  reverse-proxy:
      image: "jwilder/nginx-proxy:latest"
      container_name: "reverse-proxy"
      volumes:
        - "html:/usr/share/nginx/html"
        - "dhparam:/etc/nginx/dhparam"
        - "vhost:/etc/nginx/vhost.d"
        - "certs:/etc/nginx/certs"
        - "/run/docker.sock:/tmp/docker.sock:ro"
      restart: "always"
      environment:
        - HTTPS_METHOD=redirect
      networks: 
        - "net"
      ports:
        - "80:80"
        - "443:443"

  letsencrypt:
    image: "jrcs/letsencrypt-nginx-proxy-companion:latest"
    container_name: "letsencrypt-helper"
    volumes:
      - "html:/usr/share/nginx/html"
      - "dhparam:/etc/nginx/dhparam"
      - "vhost:/etc/nginx/vhost.d"
      - "certs:/etc/nginx/certs"
      - "/run/docker.sock:/var/run/docker.sock:ro"
    environment:
      NGINX_PROXY_CONTAINER: "reverse-proxy"
      DEFAULT_EMAIL: "myemail@test.com"
    restart: "always"
    depends_on:
      - "reverse-proxy"
    networks: 
      - "net"

volumes:
  certs:
  html:
  vhost:
  dhparam:

networks:
  net:
    external: true
	

Now under your web apps compose file section add the following lines


Dockerfile

	environment:
      - VIRTUAL_HOST=example.com
      - LETSENCRYPT_HOST=example.com
      - VIRTUAL_PORT=443
      - HTTPS_METHOD=redirect
networks: 	
      - "net"
	

So here we define the url for our certificate. That container also needs to be on the same network.

Now this doesn't even utilize the subdomain features of these packages. You can easily add another applications on subdomains and the rest is taken care of for you! I have added these lines to my nginx container for my php website as well as to various projects on subdomains.

Comments