Using TLS certificates with Nginx docker container

Marko Vuksanovic
2 min readFeb 28, 2016

--

This scenario is one you already have ran into many times. Install Nginx (or any other web server) and tell it to use TLS certificates.

The scenario that I will describe here is more and more common. We have one or more web apps that are put into a container (usually a Docker container) and then we have another container that runs some proxy to route HTTP requests to those web apps. The benefit that you get from this setup is that you can move your web apps across multiple instances in your datacenter. The only caveat is that you need to tell your proxy once you add/remove containers so it knows that it should or shouldn’t respond to those requests. Here is a really good Nginx proxy that you can use with your dockerized/containerized web apps.

Ok, now, in my previous post (https://medium.com/@mvuksano/using-let-s-encrypt-ssl-certificates-a4bf900ed2cc#.dsv1okbyh) I’ve described how you can use `letsencrypt.sh` to generate TLS certificates.

After you’re certificates are generated you can put them to use. It’s really simple. All you need to do is copy your certs to a folder. I usually put my TLS certs into `/etc/nginx/certs`.

You need to make sure that your certs have appropriate permissions. I suggest `0600` as this will make your certs only accessible to root user. You can use `chown` command to change permissions for a file.

If you’re using the Nginx proxy I suggested you also need to make sure that your public and private key, associated with a domain, follow a certain naming convention. For example, if I was deploying TLS certificates for `example.com` domain, public key which is associated with that domain needs to be named `example.com.crt` while the secret key needs to be named `example.com.key`. This means that your `/etc/nginx/certs` folder should look like this:

/etc/nginx/certs
|---- example.com.crt
|---- example.com.key

To get things working, another thing you need to is run the following command:

docker run -d -p 443:443 -v /etc/nginx/certs:/etc/nginx/certs -v /var/run/docker.sock:/tmp/docker.sock:ro jwilder/nginx-proxy

Notice how only port 443 is published. We don’t want our website to be accessible via HTTP any more (after all, it’s 2016!)

At this point, your Nginx proxy should be started and should be using your TLS certificates. Now, one last thing remains — run the actual containers which contain your web app. This task is left for the reader as an exercise :) (Hint: you can find more info here)

--

--

Marko Vuksanovic

SRE @ Google, ex-Meta, ex - ThoughtWorks. I write about managing large scale infrastructure.