Friday, June 25, 2021

Testing ssl certificate and key using nginx docker

This is assuming our certs are for www.mydomain.com, our key is domain.key and our domain cert is domain.crt.

1. Get the domain certificate and your private key. The key is generated when you generate the CSR to apply for ssl, and the certificate is sent to you from you ssl provider

$ ls 

mydomain.crt mydomain.key


2. If your provider does not provide you with the bundled certificate, you need to get the root and intermediate certificate from the provider, since nginx needs the root, intermediate and domain to be in the same file for the ssl to work.


3. Combine domain certificate, intermediate certificate and root certificate into a file, let's call the file combined.crt

$ cat mydomain.crt intermediate.crt root.crt > combined.crt


4. Remove any ^M (carriage return) characters from the combined.crt file

$ sed -i 's/\r$//' combined.crt


5. Start an nginx docker container

$ docker run -dit --name nginx -v ${PWD}:/ssl nginx:latest


6. Get the ip address of the docker container

$ docker inspect nginx | grep -w IPAddress

            "IPAddress": "172.17.0.2",

                    "IPAddress": "172.17.0.2",


7. Put the reference of our domain to the container's ip address in /etc/hosts
# cat >> /etc/hosts <<EOF
172.17.0.2 www.mydomain.com
EOF

8. Prepare an nginx config file with ssl setting
cat >> mydomain.com.conf << EOF
server {
    listen 80;
    server_name  mydomain.com;
    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }
}

server {
    listen 443 ssl;
    server_name  mydomain.com;
    ssl_certificate /ssl/combined.crt;
    ssl_certificate_key /ssl/mydomain.key;
    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }
}
EOF

9. Create a symlink for the configuration file into /etc/nginx/conf.d inside the container
docker exec -it nginx ln -s /ssl/mydomain.com.conf /etc/nginx/conf.d

10. Access bash inside the container, and test the configuration
docker exec -it nginx nginx -t

11. Restart nginx container, if the above command returned no error
$ docker restart nginx

12. Make sure the container restarted successfully
$ docker ps

13. Open up a browser and browse to https://www.mydomain.com. If all is good, you should be able to see the padlock icon beside the domain nama, and the status of the connection is secure


No comments: