DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Look, Ma! No Pods!
  • Debugging With Confidence in the Age of Observability-First Systems
  • From Zero to Production: Best Practices for Scaling LLMs in the Enterprise
  • Docker Model Runner: Streamlining AI Deployment for Developers

Trending

  • Event-Driven Architectures: Designing Scalable and Resilient Cloud Solutions
  • A Developer's Guide to Mastering Agentic AI: From Theory to Practice
  • Medallion Architecture: Why You Need It and How To Implement It With ClickHouse
  • Docker Model Runner: Streamlining AI Deployment for Developers
  1. DZone
  2. Software Design and Architecture
  3. Cloud Architecture
  4. NGINX and HTTPs With Let’s Encrypt, Certbot, and Cron Dockerization In Production

NGINX and HTTPs With Let’s Encrypt, Certbot, and Cron Dockerization In Production

Automatically create and renew website SSL certificates using the Let's Encrypt and its client certbot. Nginx server dockerization and crontab configuration.

By 
Kunkka Li user avatar
Kunkka Li
·
Updated May. 29, 21 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
69.8K Views

Join the DZone community and get the full member experience.

Join For Free

Docker is a popular open-source containerization platform and it frees your hands to build your applications in development and production. In this post, I'm going to walk you through how to build a production-grade HTTPs secured Nginx server with Docker, Docker Compose, Let’s Encrypt (its client certbot). Let’s Encrypt certificates last 90 days and will need to be renewed after the certificate expires. So I will also provide details to script the renewal in crontab in Docker container.

1. Basic Example

In development, we need a basic Nginx container without HTTPs to fast setup our local test environment. I use Nginx official docker image and wrap up all the stuff with docker-compose.

YAML
 




x



1
version: '3.4'
2

          
3
services:
4
  nginx:
5
    container_name: nginx
6
    image: nginx:stable
7
    restart: always
8
    volumes:
9
      - ./nginx/config/nginx.conf:/etc/nginx/nginx.conf
10
      - ./nginx/config/conf.d/local:/etc/nginx/conf.d
11
      - /tmp/logs/nginx:/var/log/nginx
12
      - ./nginx/html:/var/www/public/content
13
    ports:
14
      - "80:80"



I choose to use nginx.conf along with conf.d folder to manage all the configurations. So nginx.conf is for generic configuration while conf.d folder is for site specific configurations like below.

Java
 




xxxxxxxxxx
1
42


 
1
server {
2
  listen 80;
3
  server_name localhost;
4

          
5
  gzip              on;
6
  gzip_comp_level   2;
7
  gzip_min_length   1024;
8
  gzip_vary         on;
9
  gzip_proxied      expired no-cache no-store private auth;
10
  gzip_types        application/x-javascript application/javascript application/xml application/json text/xml text/css text$
11

          
12
  client_body_timeout 12;
13
  client_header_timeout 12;
14
  reset_timedout_connection on;
15
  proxy_connect_timeout       600;
16
  proxy_send_timeout          600;
17
  proxy_read_timeout          600;
18
  send_timeout                600;
19
  server_tokens off;
20
  client_max_body_size 50m;
21

          
22
  expires 1y;
23
  access_log off;
24
  log_not_found off;
25
  root /var/www/public/content;
26

          
27

          
28
  location / {
29
    proxy_pass       http://ui:3000;
30
    proxy_http_version 1.1;
31
    proxy_set_header X-Forwarded-Host $host;
32
    proxy_set_header X-Forwarded-Server $host;
33
    proxy_set_header X-Real-IP $remote_addr;
34
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
35
    proxy_set_header X-Forwarded-Proto $scheme;
36
    proxy_set_header Host $http_host;
37
    proxy_set_header Upgrade $http_upgrade;
38
    proxy_set_header Connection "Upgrade";
39
    proxy_pass_request_headers on;
40
  }
41

          
42
}



2. Configure HTTPs

2.1 Let’s Encrypt

To enable HTTPS on your website, you need to get a certificate from a Certificate Authority (CA). Let’s Encrypt is a free, automated, and open certificate authority (CA). In order to get a certificate for your website’s domain from Let’s Encrypt, you have to demonstrate control over the domain. With Let’s Encrypt, you do this using software that uses the ACME protocol which typically runs on your web host.

2.1 Certbot

we recommend using certbot-auto, which automates the process of installing Certbot on your system.The certbot-auto wrapper script installs Certbot, obtaining some dependencies from your web server OS and putting others in a python virtual environment. You can download and run it as follows. In addition, Certbot needs port 80 to be enabled, so the host firewall should allow incoming traffic on port 80 (HTTP) from anywhere. I'm using Oracle cloud, I need to open up port 80 on the security list, and also the VM firewall(as below):

Shell
 




xxxxxxxxxx
1


 
1
sudo firewall-cmd --permanent --zone=public --add-port=80/tcp
2
sudo firewall-cmd --reload



2.3 Setup NGINX

We need to configure ports, domain names, certificates as well as reverse proxy mappings for the servers. Here is a quick example grabbed from my project which contains two servers: one is for HTTPs and another is for HTTP that will redirect to HTTPs.

Java
 




x




1
server {
2
          listen 443 ssl default_server;
3
          server_name yourcompany.com;
4

          
5
          gzip              on;
6
          gzip_comp_level   2;
7
          gzip_min_length   1024;
8
          gzip_vary         on;
9
          gzip_proxied      expired no-cache no-store private auth;
10
          gzip_types        application/x-javascript application/javascript application/xml application/json text/xml text/css text$
11

          
12
          client_body_timeout 12;
13
          client_header_timeout 12;
14
          reset_timedout_connection on;
15
          proxy_connect_timeout       600;
16
          proxy_send_timeout          600;
17
          proxy_read_timeout          600;
18
          send_timeout                600;
19
          server_tokens off;
20
          client_max_body_size 50m;
21

          
22
          expires 1y;
23
          access_log off;
24
          log_not_found off;
25
          root /var/www/public/content/default;
26
          ssl_certificate    /etc/letsencrypt/live/yourcompany.com/fullchain.pem;
27
          ssl_certificate_key    /etc/letsencrypt/live/yourcompany.com/privkey.pem;
28

          
29
          location / {
30
            proxy_pass       http://ui:3000;
31
            proxy_http_version 1.1;
32
            proxy_set_header X-Forwarded-Host $host;
33
            proxy_set_header X-Forwarded-Server $host;
34
            proxy_set_header X-Real-IP $remote_addr;
35
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
36
            proxy_set_header X-Forwarded-Proto $scheme;
37
            proxy_set_header Host $http_host;
38
            proxy_set_header Upgrade $http_upgrade;
39
            proxy_set_header Connection "Upgrade";
40
            proxy_pass_request_headers on;
41
          }
42
}
43
server {
44
    listen 80;
45

          
46
    server_name yourcompany.com;
47

          
48
    return 301 https://$host$request_uri;
49
}



2.4 Automatically Renew Certificates

We just need to add the following script to crontab, which will run monthly to check and renew the certificate.

Shell
 




xxxxxxxxxx
1


 
1
@monthly /usr/local/bin/certbot-auto renew --nginx >> /var/log/cron.log 2>&1



2.5 Wrap all in Docker

We will need a Dockerfile and docker-compose.yml. 

Dockerfile

Dockerfile
 
FROM nginx:stable

ARG CERTBOT_EMAIL=info@domain.com
ARG DOMAIN_LIST

RUN  apt-get update \
      && apt-get install -y cron certbot python-certbot-nginx bash wget \
      && certbot certonly --standalone --agree-tos -m "${CERTBOT_EMAIL}" -n -d ${DOMAIN_LIST} \
      && rm -rf /var/lib/apt/lists/* \
      && echo "PATH=$PATH" > /etc/cron.d/certbot-renew  \
      && echo "@monthly certbot renew --nginx >> /var/log/cron.log 2>&1" >>/etc/cron.d/certbot-renew \
      && crontab /etc/cron.d/certbot-renew



VOLUME /etc/letsencrypt


CMD [ "sh", "-c", "cron && nginx -g 'daemon off;'" ]


docker-compose.yml

We use network mode - host at the time of docker build so that it can share host network, which is quite tricky because the port mapping(80,443) are not ready at building phrase. Otherwise, running certbot-auto will fail due to HTTP port 80 is not reachable.

YAML
 




x


 
1
version: '3.4'
2

          
3
services:
4
  nginx:
5
    container_name: nginx
6
    build:
7
      context: ./nginx
8
      network: host
9
      args:
10
        - CERTBOT_EMAIL=hello@yourcompany.com #replace with your own email
11
        - DOMAIN_LIST=yourcompany.com,api.yourcompany.com,www.yourcompany.com #replace with your own domains
12
    restart: always
13
    volumes:
14
      - ./nginx/config/conf.d/prod:/etc/nginx/conf.d
15
      - letsencrypt:/etc/letsencrypt
16
    ports:
17
      - "80:80"
18
      - "443:443"



That's it. You're good to go. Contact me if you need the whole source code.

Docker (software) Production (computer science)

Published at DZone with permission of Kunkka Li. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Look, Ma! No Pods!
  • Debugging With Confidence in the Age of Observability-First Systems
  • From Zero to Production: Best Practices for Scaling LLMs in the Enterprise
  • Docker Model Runner: Streamlining AI Deployment for Developers

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!