How to Deploy a Secure Dockerized Web App with Nginx Reverse Proxy

Configurare noua (How To)

Situatie

What You’ll Build

  • A web application container (Python Flask example)

  • An Nginx reverse-proxy container

  • Automatic SSL using Let’s Encrypt

  • A single docker-compose.yml stack

Solutie

Part 1: Prepare Your Server

Step 1 — Install Docker & Docker Compose

Ubuntu example:

sudo apt update
sudo apt install docker.io docker-compose -y

Step 2 — Create a Project Folder

mkdir /opt/webstack
cd /opt/webstack

Part 2: Create the Application Container

Step 1 — Make a Simple Flask App

app/app.py:

from flask import Flask
app = Flask(__name__)
@app.route(“/”)
def home():
return “Welcome to your Dockerized Web App!”

if __name__ == “__main__”:
app.run(host=“0.0.0.0”, port=5000)

Step 2 — Add a Dockerfile

app/Dockerfile:

FROM python:3.11
WORKDIR /app
COPY . .
RUN pip install flask
CMD ["python", "app.py"]

Part 3: Configure Nginx Reverse Proxy

Create Nginx Configuration

nginx/default.conf:

server {
listen 80;
server_name yourdomain.com;
location / {
proxy_pass http://app:5000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}

Part 4: Build Docker Compose Stack

docker-compose.yml

version: '3'

services:
app:
build: ./app
container_name: flask_app

nginx:
image: nginx
container_name: nginx_proxy
ports:
“80:80”
“443:443”
volumes:
./nginx:/etc/nginx/conf.d
./certbot:/etc/letsencrypt
depends_on:
app

certbot:
image: certbot/certbot
command: certonly –webroot –webroot-path=/var/www/html –email you@domain.com –agree-tos -d yourdomain.com
volumes:
./certbot:/etc/letsencrypt
./nginx:/var/www/html

Part 5: Launch the Stack

Build and run:

docker-compose up -d

Part 6: Enable HTTPS

Run Certbot:

docker-compose run --rm certbot

Restart Nginx:

docker-compose restart nginx

Security Hardening Tips

  • Enable auto-renewal for SSL using a cron job

  • Limit container privileges using read_only: true

  • Use fail2ban to protect SSH

  • Place Nginx behind Cloudflare if desired

Optional Add-Ons

  • Add a Postgres or Redis service

  • Implement load-balancing with Nginx upstream blocks

  • Add GitHub Actions CI/CD pipeline to rebuild images automatically.

Tip solutie

Permanent

Voteaza

(14 din 23 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?