Dansp
Dansp

Reputation: 1745

How to implement (Certbot) ssl using Docker with Nginx image

I'm trying to implement ssl in my application using Docker with nginx image. I have two apps, one for back-end (api) and other for front-end (admin). It's working with http on port 80, but I need to use https. This is my nginx config file...

upstream ulib-api {
  server 10.0.2.229:8001;
}

server {
  listen 80;
  server_name api.ulib.com.br;

  location / {
      proxy_pass http://ulib-api;
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-Host $host;
      proxy_set_header X-Forwarded-Server $host;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  }

  client_max_body_size 100M;
}

upstream ulib-admin {
  server 10.0.2.229:8002;
}

server {
  listen 80;
  server_name admin.ulib.com.br;

  location / {
      proxy_pass http://ulib-admin;
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-Host $host;
      proxy_set_header X-Forwarded-Server $host;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  }

  client_max_body_size 100M;
}

I get some tutorials but all is using docker-compose. I need to install it with Dockerfile. Can anyone give me a light?

... I'm using ECS instance on AWS and project is building with CI/CD

Upvotes: 1

Views: 2220

Answers (1)

grapes
grapes

Reputation: 8636

This is just one of possible ways:

First issue certificate using certbot. You will end up with a couple of *.pem files. There are pretty tutorials on installing and running certbot on different systems, I used Ubuntu with command certbot --nginx certonly. You need to run this command on your domain because certbot will check that you are the owner of the domain by a number of challenges.

Second, you create nginx containers. You will need proper nginx.conf and link certificates to this containers. I use docker volumes but that is not the only way.

My nginx.conf looks like following:

http {
    server {
        listen 443 ssl;

        ssl_certificate /cert/<yourdomain.com>/fullchain.pem;
        ssl_certificate_key /cert/<yourdomain.com>/privkey.pem;
        ssl_trusted_certificate /cert/<yourdomain.com>/chain.pem;
        ssl_protocols SSLv3 TLSv1 TLSv1.1 TLSv1.2;
        ...
    }
}

Last, you run nginx with proper volumes connected:

docker run -d -v $PWD/nginx.conf:/etc/nginx/nginx.conf:ro -v $PWD/cert:/cert:ro -p 443:443 nginx:1.15-alpine 

Notice:

  • I mapped $PWD/cert into container as /cert. This is a folder, where *.pem files are stored. They live under ./cert/example.com/*.pem

  • Inside nginx.conf you refer these certificates with ssl_... directives

  • You should expose port 443 to be able to connect

Upvotes: 1

Related Questions