DevOps

Easily generate SSL certificates and htpasswd files with Docker

So you don’t have installed OpenSSL or apache2-utils on your laptop, but you have Docker installed and you want to generate SSL (self-signed or not) certificates and an htpasswd file for basic authentication ?
Follow those easy steps!

Generate SSL certificates from a Docker container

I gathered those steps from this nice article from Digital Ocean (How To Create a SSL Certificate on nginx for Ubuntu 12.04) and I adapted them to run all the commands inside a container.

You’ll notice the use of a volume that mounts the current directory into the container /work directory (by default a volume is read write):

  1. First we generate a private key:
    docker run -v $PWD:/work -it nginx openssl genrsa -des3 -out /work/server.key.protected 2048
  2. Then we generate a Certificate Signing Request:
    docker run -v $PWD:/work -it nginx openssl req -new -key /work/server.key.protected -out /work/server.csr
  3. After that we generate a password-less key, for the use of use with webservers:
    docker run -v $PWD:/work -it nginx openssl rsa -in /work/server.key.protected -out /work/server.key
  4. And finally we sign the certificate (since we want a self signed certificate)
    docker run -v $PWD:/work -it nginx openssl x509 -req -days 365 -in /work/server.csr -signkey /work/server.key -out /work/server.crt

Now have a look at your current folder, you should see:

server.crt server.csr server.key server.key.protected

Usually, the key and crt files are enough to serve HTTPS content using nginx or apache2

Generate a htpasswd file from a Docker container

htpasswd files are used for basic authentication in Nginx and Apache2.

Usually you would install apache2-utils on your Linux host to use the tool named htpasswd, but actually openssl can generate those files too, as explained in Nginx FAQ

Well, you still need to install openssl (or apache2-utils) in that case, unless you rely on a container to create your htpasswd:

docker run -it nginx printf "John:$(openssl passwd -crypt V3Ry)\n" >> .htpasswd

That’s it ! No need to use a volume this time since we just piped the output of the command to a file hosted on the host.

You can use cat to see its content:

cat .htpasswd
John:yJpIVR3CZL9tU

So next time you install a tool for a task, ask yourself whether or not a Docker image already provides this image for you, instead of polluting your laptop system with software you’ll use just once!

Anthony Dahanne

Anthony Dahanne is a Java software developer for 8 years, his favorite topics are Android, building tools, Continuous Integration and, of course, core Java development. Working for Terracotta, he currently implements the REST management interface for EhCache.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button