Unverified Commit 4480b64e authored by Grant Birkinbine's avatar Grant Birkinbine Committed by GitHub
Browse files

init (#120)

Signed-off-by: default avatarGrant Birkinbine <grant.birkinbine@gmail.com>
parent a42a8531
# Compose Sample Application
## NGINX Reverse Proxy -> WSGI -> Python/Flask Backend
Project structure:
├── docker-compose.yaml
├── flask
│   ├── app.py
│   ├── Dockerfile
│   ├── requirements.txt
│   └── wsgi.py
└── nginx
├── default.conf
├── Dockerfile
├── nginx.conf
   └── start.sh
build: nginx
- 80:80
build: flask
The compose file defines an application with two services `nginx-proxy` and `flask-app`.
When deploying the application, docker-compose maps port 80 of the web service container to port 80 of the host as specified in the file.
Make sure port 80 on the host is not being used by another container, otherwise the port should be changed.
## Deploy with docker-compose
$ docker-compose up -d
Creating network "nginx-wsgi-flask_default" with the default driver
Building flask-app
Building nginx-proxy
Creating nginx-wsgi-flask_flask-app_1 ... done
Creating nginx-wsgi-flask_nginx-proxy_1 ... done
## Expected result
Listing containers must show two containers running and the port mapping as below:
$ docker ps
bde3f29cf571 ...nginx-proxy "/docker-entrypoint.…" About a minute ago Up About a minute (healthy)>80/tcp ...nginx-proxy_1
86c44470b547 ...flask-app "gunicorn -w 3 -t 60…" About a minute ago Up About a minute (healthy) 5000/tcp,>8000/tcp ...flask-app_1
After the application starts, navigate to `http://localhost:80` in your web browser or run:
$ curl localhost:80
Hello World!
Stop and remove the containers
$ docker-compose down
Stopping nginx-wsgi-flask_nginx-proxy_1 ... done
Stopping nginx-wsgi-flask_flask-app_1 ... done
Removing nginx-wsgi-flask_nginx-proxy_1 ... done
Removing nginx-wsgi-flask_flask-app_1 ... done
Removing network nginx-wsgi-flask_default
## About
By following the steps above, you will have an NGINX Reverse Proxy and a Flask backend. The general traffic flow will look like the following:
`Client -> NGINX -> WSGI -> Flask`
With this deployment model, we use NGINX to proxy and handle all requests to our Flask backend. This is a powerful deployment model as we can use NGINX to cache responses or even act as an application load balancer between multiple Flask backends. You could also integrate a Web Application Firewall into NGINX to protect your Flask backend from attacks.
### WSGI
WSGI (Web Server Gateway Interface) is the interface that sits in between our NGINX proxy and Flask backend. It is used to handle requests and interface with our backend. WSGI allows you to handle thousands of requests at a time and is highly scalable. In this `docker-compose` sample, we use Gunicorn for our WSGI.
### Flask
Flask is a web development framework written in Python. It is the "backend" which processes requests.
A couple of sample endpoints are provided in this `docker-compose` example:
* `/` - Returns a "Hello World!" string.
* `/cache-me` - Returns a string which is cached by the NGINX reverse proxy. This demonstrates an intermediary cache implementation.
* `/info` - Returns informational headers about the request. Some are passed from NGINX for added client visibility.
version: "3.7"
build: nginx
restart: always
- ./nginx/default.conf:/tmp/default.conf
- FLASK_SERVER_ADDR=flask-app:8000
- "80:80"
- flask-app
test: ["CMD-SHELL", "curl --silent --fail localhost:80/health-check || exit 1"]
interval: 10s
timeout: 10s
retries: 3
command: /app/start.sh
build: flask
restart: always
- '8000:8000'
test: ["CMD-SHELL", "curl --silent --fail localhost:8000/flask-health-check || exit 1"]
interval: 10s
timeout: 10s
retries: 3
command: gunicorn -w 3 -t 60 -b app:app
FROM python:3.9.2-alpine
# upgrade pip
RUN pip install --upgrade pip
# get curl for healthchecks
RUN apk add curl
# permissions and nonroot user for tightened security
RUN adduser -D nonroot
RUN mkdir /home/app/ && chown -R nonroot:nonroot /home/app
RUN mkdir -p /var/log/flask-app && touch /var/log/flask-app/flask-app.err.log && touch /var/log/flask-app/flask-app.out.log
RUN chown -R nonroot:nonroot /var/log/flask-app
WORKDIR /home/app
USER nonroot
# copy all the files to the container
COPY --chown=nonroot:nonroot . .
# venv
ENV VIRTUAL_ENV=/home/app/venv
# python setup
RUN python -m venv $VIRTUAL_ENV
RUN export FLASK_APP=app.py
RUN pip install -r requirements.txt
# define the port number the container should expose
CMD ["python", "app.py"]
\ No newline at end of file
from flask import Flask, request, jsonify
app = Flask(__name__)
def hello():
return "Hello World!"
def cache():
return "nginx will cache this response"
def info():
resp = {
'connecting_ip': request.headers['X-Real-IP'],
'proxy_ip': request.headers['X-Forwarded-For'],
'host': request.headers['Host'],
'user-agent': request.headers['User-Agent']
return jsonify(resp)
def flask_health_check():
return "success"
\ No newline at end of file
from app import app
import os
if __name__ == "__main__":
app.run(host='', port=os.environ.get("FLASK_SERVER_PORT"), debug=True)
FROM nginx:1.19.7-alpine
# Add bash for boot cmd
RUN apk add bash
# Add nginx.conf to container
COPY --chown=nginx:nginx nginx.conf /etc/nginx/nginx.conf
COPY --chown=nginx:nginx start.sh /app/start.sh
# set workdir
# permissions and nginx user for tightened security
RUN chown -R nginx:nginx /app && chmod -R 755 /app && \
chown -R nginx:nginx /var/cache/nginx && \
chown -R nginx:nginx /var/log/nginx && \
chmod -R 755 /var/log/nginx; \
chown -R nginx:nginx /etc/nginx/conf.d
RUN touch /var/run/nginx.pid && chown -R nginx:nginx /var/run/nginx.pid
# # Uncomment to keep the nginx logs inside the container - Leave commented for logging to stdout and stderr
# RUN mkdir -p /var/log/nginx
# RUN unlink /var/log/nginx/access.log \
# && unlink /var/log/nginx/error.log \
# && touch /var/log/nginx/access.log \
# && touch /var/log/nginx/error.log \
# && chown nginx /var/log/nginx/*log \
# && chmod 644 /var/log/nginx/*log
USER nginx
CMD ["nginx", "-g", "'daemon off;'"]
proxy_cache_path /tmp/cache levels=1:2 keys_zone=cache:10m max_size=500m inactive=60m use_temp_path=off;
server {
listen 80;
location / {
proxy_pass http://$FLASK_SERVER_ADDR;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
location /cache-me {
proxy_pass http://$FLASK_SERVER_ADDR;
proxy_cache cache;
proxy_cache_lock on;
proxy_cache_valid 200 30s;
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
proxy_cache_revalidate on;
proxy_cache_background_update on;
expires 20s;
location /health-check {
add_header Content-Type text/plain;
return 200 "success";
worker_processes auto;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
# Define the format of log messages.
log_format main_ext '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" '
'"$host" sn="$server_name" '
'rt=$request_time '
'ua="$upstream_addr" us="$upstream_status" '
'ut="$upstream_response_time" ul="$upstream_response_length" '
'cs=$upstream_cache_status' ;
access_log /var/log/nginx/access.log main_ext;
error_log /var/log/nginx/error.log warn;
sendfile on;
keepalive_timeout 65;
# Enable Compression
gzip on;
# Disable Display of NGINX Version
server_tokens off;
# Size Limits
client_body_buffer_size 10K;
client_header_buffer_size 1k;
client_max_body_size 8m;
large_client_header_buffers 2 1k;
# # SSL / TLS Settings - Suggested for Security
# ssl_protocols TLSv1.2 TLSv1.3;
# ssl_session_timeout 15m;
# ssl_prefer_server_ciphers on;
# ssl_session_tickets off;
include /etc/nginx/conf.d/*.conf;
envsubst '$FLASK_SERVER_ADDR' < /tmp/default.conf > /etc/nginx/conf.d/default.conf && nginx -g 'daemon off;'
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment