├── tests
├── __init__.py
├── .gitignore
├── test_01_main
│ ├── __init__.py
│ ├── test_defaults_01.py
│ └── test_env_vars_03.py
├── test_02_app
│ ├── __init__.py
│ ├── custom_app
│ │ ├── application
│ │ │ └── custom_app
│ │ │ │ ├── __init__.py
│ │ │ │ ├── content
│ │ │ │ ├── test.txt
│ │ │ │ └── index.html
│ │ │ │ ├── uwsgi.ini
│ │ │ │ └── main.py
│ │ └── prestart.sh
│ ├── simple_app
│ │ └── app
│ │ │ ├── static
│ │ │ └── test.txt
│ │ │ └── main.py
│ ├── custom_nginx_app
│ │ └── app
│ │ │ ├── main.py
│ │ │ └── nginx.conf
│ ├── test_simple_app.py
│ ├── test_custom_ngnix_app.py
│ └── test_app_and_env_vars.py
└── utils.py
├── .github
├── FUNDING.yml
├── dependabot.yml
├── ISSUE_TEMPLATE
│ ├── config.yml
│ └── privileged.yml
├── workflows
│ ├── latest-changes.yml
│ ├── issue-manager.yml
│ ├── test.yml
│ └── deploy.yml
└── DISCUSSION_TEMPLATE
│ └── questions.yml
├── docker-images
├── requirements.txt
├── app
│ ├── uwsgi.ini
│ ├── prestart.sh
│ └── main.py
├── python3.9.dockerfile
├── python3.10.dockerfile
├── python3.11.dockerfile
├── python3.12.dockerfile
└── entrypoint.sh
├── mypy.ini
├── scripts
├── test.sh
├── lint.sh
├── format-imports.sh
├── format.sh
└── process_all.py
├── pyproject.toml
├── SECURITY.md
├── .gitignore
├── LICENSE.txt
└── README.md
/tests/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/tests/.gitignore:
--------------------------------------------------------------------------------
1 | Dockerfile
2 |
--------------------------------------------------------------------------------
/tests/test_01_main/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/tests/test_02_app/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | github: [tiangolo]
2 |
--------------------------------------------------------------------------------
/docker-images/requirements.txt:
--------------------------------------------------------------------------------
1 | flask==2.2.5
2 |
--------------------------------------------------------------------------------
/tests/test_02_app/custom_app/application/custom_app/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/tests/test_02_app/simple_app/app/static/test.txt:
--------------------------------------------------------------------------------
1 | Static test
--------------------------------------------------------------------------------
/docker-images/app/uwsgi.ini:
--------------------------------------------------------------------------------
1 | [uwsgi]
2 | module = main
3 | callable = app
4 |
--------------------------------------------------------------------------------
/tests/test_02_app/custom_app/application/custom_app/content/test.txt:
--------------------------------------------------------------------------------
1 | Static test
--------------------------------------------------------------------------------
/mypy.ini:
--------------------------------------------------------------------------------
1 | [mypy]
2 | disallow_untyped_defs = True
3 | ignore_missing_imports = True
4 |
--------------------------------------------------------------------------------
/scripts/test.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | set -e
3 |
4 | SLEEP_TIME=5 pytest tests
5 |
--------------------------------------------------------------------------------
/tests/test_02_app/custom_app/prestart.sh:
--------------------------------------------------------------------------------
1 | #! /usr/bin/env bash
2 | echo "custom prestart.sh running"
3 |
--------------------------------------------------------------------------------
/tests/test_02_app/custom_app/application/custom_app/content/index.html:
--------------------------------------------------------------------------------
1 |
Hello World from HTML test
--------------------------------------------------------------------------------
/tests/test_02_app/custom_app/application/custom_app/uwsgi.ini:
--------------------------------------------------------------------------------
1 | [uwsgi]
2 | module = custom_app.main
3 | callable = custom_app
4 | enable-threads = true
5 |
--------------------------------------------------------------------------------
/scripts/lint.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | set -e
4 | set -x
5 |
6 | mypy ./
7 | black ./ --check
8 | isort --multi-line=3 --trailing-comma --force-grid-wrap=0 --combine-as --line-width 88 --recursive --check-only
9 |
--------------------------------------------------------------------------------
/scripts/format-imports.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | set -x
3 |
4 | # Sort imports one per line, so autoflake can remove unused imports
5 | isort --recursive --force-single-line-imports --apply ./
6 | sh ./scripts/format.sh
7 |
--------------------------------------------------------------------------------
/docker-images/app/prestart.sh:
--------------------------------------------------------------------------------
1 | #! /usr/bin/env sh
2 |
3 | echo "Running inside /app/prestart.sh, you could add migrations to this file, e.g.:"
4 |
5 | echo "
6 | #! /usr/bin/env sh
7 |
8 | # Let the DB start
9 | sleep 10;
10 | # Run migrations
11 | alembic upgrade head
12 | "
13 |
--------------------------------------------------------------------------------
/scripts/format.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | set -x
4 |
5 | autoflake --remove-all-unused-imports --recursive --remove-unused-variables --in-place ./ --exclude=__init__.py
6 | isort --multi-line=3 --trailing-comma --force-grid-wrap=0 --combine-as --line-width 88 --recursive --apply ./
7 | black ./
8 |
--------------------------------------------------------------------------------
/.github/dependabot.yml:
--------------------------------------------------------------------------------
1 | version: 2
2 | updates:
3 | # GitHub Actions
4 | - package-ecosystem: "github-actions"
5 | directory: "/"
6 | schedule:
7 | interval: "daily"
8 | commit-message:
9 | prefix: ⬆
10 | # Python
11 | - package-ecosystem: "pip"
12 | directory: "/"
13 | schedule:
14 | interval: "daily"
15 | commit-message:
16 | prefix: ⬆
17 |
--------------------------------------------------------------------------------
/docker-images/app/main.py:
--------------------------------------------------------------------------------
1 | import sys
2 |
3 | from flask import Flask
4 |
5 | app = Flask(__name__)
6 |
7 |
8 | @app.route("/")
9 | def hello():
10 | version = "{}.{}".format(sys.version_info.major, sys.version_info.minor)
11 | message = "Hello World from Flask in a uWSGI Nginx Docker container with Python {} (default)".format(
12 | version
13 | )
14 | return message
15 |
16 |
17 | if __name__ == "__main__":
18 | app.run(host="0.0.0.0", debug=True, port=80)
19 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [tool.poetry]
2 | name = "uwsgi-nginx-flask-docker"
3 | version = "0.1.0"
4 | description = "Docker image with uWSGI and Nginx for Flask applications in Python running in a single container."
5 | authors = ["Sebastián Ramírez "]
6 | license = "MIT"
7 |
8 | [tool.poetry.dependencies]
9 | python = "^3.7"
10 | docker = "^6.0.1"
11 | pytest = "^7.0.1"
12 |
13 | [tool.poetry.dev-dependencies]
14 | black = "^23.1"
15 | isort = "^5.8.0"
16 | autoflake = "^2.0.0"
17 | mypy = "^1.1"
18 |
19 | [build-system]
20 | requires = ["poetry>=0.12"]
21 | build-backend = "poetry.masonry.api"
22 |
--------------------------------------------------------------------------------
/tests/test_02_app/custom_nginx_app/app/main.py:
--------------------------------------------------------------------------------
1 | import sys
2 |
3 | from flask import Flask
4 |
5 | app = Flask(__name__)
6 |
7 |
8 | @app.route("/")
9 | def hello():
10 | version = "{}.{}".format(sys.version_info.major, sys.version_info.minor)
11 | message = "Hello World from Flask in a uWSGI Nginx Docker container with Python {} - testing".format(
12 | version
13 | )
14 | return message
15 |
16 |
17 | @app.route("/static/test.txt")
18 | def static_test():
19 | return "Static, from Flask"
20 |
21 |
22 | if __name__ == "__main__":
23 | app.run(host="0.0.0.0", debug=True, port=80)
24 |
--------------------------------------------------------------------------------
/tests/test_02_app/simple_app/app/main.py:
--------------------------------------------------------------------------------
1 | import sys
2 |
3 | from flask import Flask
4 |
5 | app = Flask(__name__)
6 |
7 |
8 | @app.route("/")
9 | def hello():
10 | version = "{}.{}".format(sys.version_info.major, sys.version_info.minor)
11 | message = "Hello World from Flask in a uWSGI Nginx Docker container with Python {} - testing".format(
12 | version
13 | )
14 | return message
15 |
16 |
17 | @app.route("/static/test.txt")
18 | def static_test():
19 | return "Not run, Nginx overrides to serve static file"
20 |
21 |
22 | if __name__ == "__main__":
23 | app.run(host="0.0.0.0", debug=True, port=80)
24 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/config.yml:
--------------------------------------------------------------------------------
1 | blank_issues_enabled: false
2 | contact_links:
3 | - name: Security Contact
4 | about: Please report security vulnerabilities to security@tiangolo.com
5 | - name: Question or Problem
6 | about: Ask a question or ask about a problem in GitHub Discussions.
7 | url: https://github.com/tiangolo/uwsgi-nginx-flask-docker/discussions/categories/questions
8 | - name: Feature Request
9 | about: To suggest an idea or ask about a feature, please start with a question saying what you would like to achieve. There might be a way to do it already.
10 | url: https://github.com/tiangolo/uwsgi-nginx-flask-docker/discussions/categories/questions
11 |
--------------------------------------------------------------------------------
/tests/test_02_app/custom_app/application/custom_app/main.py:
--------------------------------------------------------------------------------
1 | import sys
2 |
3 | from flask import Flask
4 |
5 | custom_app = Flask(__name__)
6 |
7 |
8 | @custom_app.route("/api")
9 | def hello():
10 | version = "{}.{}".format(sys.version_info.major, sys.version_info.minor)
11 | message = "Hello World from Flask in a uWSGI Nginx Docker container with Python {} - testing".format(
12 | version
13 | )
14 | return message
15 |
16 |
17 | @custom_app.route("/")
18 | def main():
19 | return "API response overriden by Nginx"
20 |
21 |
22 | @custom_app.route("/content/test.txt")
23 | def static_test():
24 | return "Not run, Nginx overrides to serve static file"
25 |
26 |
27 | if __name__ == "__main__":
28 | custom_app.run(host="0.0.0.0", debug=True, port=80)
29 |
--------------------------------------------------------------------------------
/.github/workflows/latest-changes.yml:
--------------------------------------------------------------------------------
1 | name: Latest Changes
2 |
3 | on:
4 | pull_request_target:
5 | branches:
6 | - master
7 | types:
8 | - closed
9 | workflow_dispatch:
10 | inputs:
11 | number:
12 | description: PR number
13 | required: true
14 | debug_enabled:
15 | description: 'Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate)'
16 | required: false
17 | default: 'false'
18 |
19 | jobs:
20 | latest-changes:
21 | runs-on: ubuntu-latest
22 | steps:
23 | - uses: actions/checkout@v4
24 | with:
25 | # To allow latest-changes to commit to master
26 | token: ${{ secrets.UWSGI_NGINX_FLASK_DOCKER_LATEST_CHANGES }}
27 | - uses: tiangolo/latest-changes@0.3.1
28 | with:
29 | token: ${{ secrets.GITHUB_TOKEN }}
30 |
--------------------------------------------------------------------------------
/tests/test_02_app/custom_nginx_app/app/nginx.conf:
--------------------------------------------------------------------------------
1 | user nginx;
2 | worker_processes 2;
3 | error_log /var/log/nginx/error.log warn;
4 | pid /var/run/nginx.pid;
5 | events {
6 | worker_connections 2048;
7 | }
8 | http {
9 | include /etc/nginx/mime.types;
10 | default_type application/octet-stream;
11 | log_format main '$remote_addr - $remote_user [$time_local] "$request" '
12 | '$status $body_bytes_sent "$http_referer" '
13 | '"$http_user_agent" "$http_x_forwarded_for"';
14 | access_log /var/log/nginx/access.log main;
15 | sendfile on;
16 | keepalive_timeout 300;
17 | server {
18 | listen 8080;
19 | location / {
20 | try_files $uri @app;
21 | }
22 | location @app {
23 | include uwsgi_params;
24 | uwsgi_pass unix:///tmp/uwsgi.sock;
25 | }
26 | }
27 | }
28 | daemon off;
29 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/privileged.yml:
--------------------------------------------------------------------------------
1 | name: Privileged
2 | description: You are @tiangolo or he asked you directly to create an issue here. If not, check the other options. 👇
3 | body:
4 | - type: markdown
5 | attributes:
6 | value: |
7 | Thanks for your interest in this project! 🚀
8 |
9 | If you are not @tiangolo or he didn't ask you directly to create an issue here, please start the conversation in a [Question in GitHub Discussions](https://github.com/tiangolo/uwsgi-nginx-flask-docker/discussions/categories/questions) instead.
10 | - type: checkboxes
11 | id: privileged
12 | attributes:
13 | label: Privileged issue
14 | description: Confirm that you are allowed to create an issue here.
15 | options:
16 | - label: I'm @tiangolo or he asked me directly to create an issue here.
17 | required: true
18 | - type: textarea
19 | id: content
20 | attributes:
21 | label: Issue Content
22 | description: Add the content of the issue here.
23 |
--------------------------------------------------------------------------------
/.github/workflows/issue-manager.yml:
--------------------------------------------------------------------------------
1 | name: Issue Manager
2 |
3 | on:
4 | schedule:
5 | - cron: "15 9 * * *"
6 | issue_comment:
7 | types:
8 | - created
9 | issues:
10 | types:
11 | - labeled
12 | pull_request_target:
13 | types:
14 | - labeled
15 | workflow_dispatch:
16 |
17 | permissions:
18 | issues: write
19 | pull-requests: write
20 |
21 | jobs:
22 | issue-manager:
23 | runs-on: ubuntu-latest
24 | steps:
25 | - uses: tiangolo/issue-manager@0.5.1
26 | with:
27 | token: ${{ secrets.GITHUB_TOKEN }}
28 | config: >
29 | {
30 | "answered": {
31 | "delay": 864000,
32 | "message": "Assuming the original need was handled, this will be automatically closed now. But feel free to add more comments or create new issues or PRs."
33 | },
34 | "waiting": {
35 | "delay": 2628000,
36 | "message": "As this PR has been waiting for the original user for a while but seems to be inactive, it's now going to be closed. But if there's anyone interested, feel free to create a new PR."
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/SECURITY.md:
--------------------------------------------------------------------------------
1 | # Security Policy
2 |
3 | Security is very important for this project and its community. 🔒
4 |
5 | Learn more about it below. 👇
6 |
7 | ## Versions
8 |
9 | The latest version or release is supported.
10 |
11 | You are encouraged to write tests for your application and update your versions frequently after ensuring that your tests are passing. This way you will benefit from the latest features, bug fixes, and **security fixes**.
12 |
13 | ## Reporting a Vulnerability
14 |
15 | If you think you found a vulnerability, and even if you are not sure about it, please report it right away by sending an email to: security@tiangolo.com. Please try to be as explicit as possible, describing all the steps and example code to reproduce the security issue.
16 |
17 | I (the author, [@tiangolo](https://twitter.com/tiangolo)) will review it thoroughly and get back to you.
18 |
19 | ## Public Discussions
20 |
21 | Please restrain from publicly discussing a potential security vulnerability. 🙊
22 |
23 | It's better to discuss privately and try to find a solution first, to limit the potential impact as much as possible.
24 |
25 | ---
26 |
27 | Thanks for your help!
28 |
29 | The community and I thank you for that. 🙇
30 |
--------------------------------------------------------------------------------
/docker-images/python3.9.dockerfile:
--------------------------------------------------------------------------------
1 | FROM tiangolo/uwsgi-nginx:python3.9
2 |
3 | LABEL maintainer="Sebastian Ramirez "
4 |
5 | # Install requirements
6 | COPY requirements.txt /tmp/requirements.txt
7 | RUN pip install --no-cache-dir -r /tmp/requirements.txt
8 |
9 | # URL under which static (not modified by Python) files will be requested
10 | # They will be served by Nginx directly, without being handled by uWSGI
11 | ENV STATIC_URL /static
12 | # Absolute path in where the static files wil be
13 | ENV STATIC_PATH /app/static
14 |
15 | # If STATIC_INDEX is 1, serve / with /static/index.html directly (or the static URL configured)
16 | # ENV STATIC_INDEX 1
17 | ENV STATIC_INDEX 0
18 |
19 | # Add demo app
20 | COPY ./app /app
21 | WORKDIR /app
22 |
23 | # Make /app/* available to be imported by Python globally to better support several use cases like Alembic migrations.
24 | ENV PYTHONPATH=/app
25 |
26 | # Move the base entrypoint to reuse it
27 | RUN mv /entrypoint.sh /uwsgi-nginx-entrypoint.sh
28 | # Copy the entrypoint that will generate Nginx additional configs
29 | COPY entrypoint.sh /entrypoint.sh
30 | RUN chmod +x /entrypoint.sh
31 |
32 | ENTRYPOINT ["/entrypoint.sh"]
33 |
34 | # Run the start script provided by the parent image tiangolo/uwsgi-nginx.
35 | # It will check for an /app/prestart.sh script (e.g. for migrations)
36 | # And then will start Supervisor, which in turn will start Nginx and uWSGI
37 | CMD ["/start.sh"]
38 |
--------------------------------------------------------------------------------
/docker-images/python3.10.dockerfile:
--------------------------------------------------------------------------------
1 | FROM tiangolo/uwsgi-nginx:python3.10
2 |
3 | LABEL maintainer="Sebastian Ramirez "
4 |
5 | # Install requirements
6 | COPY requirements.txt /tmp/requirements.txt
7 | RUN pip install --no-cache-dir -r /tmp/requirements.txt
8 |
9 | # URL under which static (not modified by Python) files will be requested
10 | # They will be served by Nginx directly, without being handled by uWSGI
11 | ENV STATIC_URL /static
12 | # Absolute path in where the static files wil be
13 | ENV STATIC_PATH /app/static
14 |
15 | # If STATIC_INDEX is 1, serve / with /static/index.html directly (or the static URL configured)
16 | # ENV STATIC_INDEX 1
17 | ENV STATIC_INDEX 0
18 |
19 | # Add demo app
20 | COPY ./app /app
21 | WORKDIR /app
22 |
23 | # Make /app/* available to be imported by Python globally to better support several use cases like Alembic migrations.
24 | ENV PYTHONPATH=/app
25 |
26 | # Move the base entrypoint to reuse it
27 | RUN mv /entrypoint.sh /uwsgi-nginx-entrypoint.sh
28 | # Copy the entrypoint that will generate Nginx additional configs
29 | COPY entrypoint.sh /entrypoint.sh
30 | RUN chmod +x /entrypoint.sh
31 |
32 | ENTRYPOINT ["/entrypoint.sh"]
33 |
34 | # Run the start script provided by the parent image tiangolo/uwsgi-nginx.
35 | # It will check for an /app/prestart.sh script (e.g. for migrations)
36 | # And then will start Supervisor, which in turn will start Nginx and uWSGI
37 | CMD ["/start.sh"]
38 |
--------------------------------------------------------------------------------
/docker-images/python3.11.dockerfile:
--------------------------------------------------------------------------------
1 | FROM tiangolo/uwsgi-nginx:python3.11
2 |
3 | LABEL maintainer="Sebastian Ramirez "
4 |
5 | # Install requirements
6 | COPY requirements.txt /tmp/requirements.txt
7 | RUN pip install --no-cache-dir -r /tmp/requirements.txt
8 |
9 | # URL under which static (not modified by Python) files will be requested
10 | # They will be served by Nginx directly, without being handled by uWSGI
11 | ENV STATIC_URL /static
12 | # Absolute path in where the static files wil be
13 | ENV STATIC_PATH /app/static
14 |
15 | # If STATIC_INDEX is 1, serve / with /static/index.html directly (or the static URL configured)
16 | # ENV STATIC_INDEX 1
17 | ENV STATIC_INDEX 0
18 |
19 | # Add demo app
20 | COPY ./app /app
21 | WORKDIR /app
22 |
23 | # Make /app/* available to be imported by Python globally to better support several use cases like Alembic migrations.
24 | ENV PYTHONPATH=/app
25 |
26 | # Move the base entrypoint to reuse it
27 | RUN mv /entrypoint.sh /uwsgi-nginx-entrypoint.sh
28 | # Copy the entrypoint that will generate Nginx additional configs
29 | COPY entrypoint.sh /entrypoint.sh
30 | RUN chmod +x /entrypoint.sh
31 |
32 | ENTRYPOINT ["/entrypoint.sh"]
33 |
34 | # Run the start script provided by the parent image tiangolo/uwsgi-nginx.
35 | # It will check for an /app/prestart.sh script (e.g. for migrations)
36 | # And then will start Supervisor, which in turn will start Nginx and uWSGI
37 | CMD ["/start.sh"]
38 |
--------------------------------------------------------------------------------
/docker-images/python3.12.dockerfile:
--------------------------------------------------------------------------------
1 | FROM tiangolo/uwsgi-nginx:python3.12
2 |
3 | LABEL maintainer="Sebastian Ramirez "
4 |
5 | # Install requirements
6 | COPY requirements.txt /tmp/requirements.txt
7 | RUN pip install --no-cache-dir -r /tmp/requirements.txt
8 |
9 | # URL under which static (not modified by Python) files will be requested
10 | # They will be served by Nginx directly, without being handled by uWSGI
11 | ENV STATIC_URL /static
12 | # Absolute path in where the static files wil be
13 | ENV STATIC_PATH /app/static
14 |
15 | # If STATIC_INDEX is 1, serve / with /static/index.html directly (or the static URL configured)
16 | # ENV STATIC_INDEX 1
17 | ENV STATIC_INDEX 0
18 |
19 | # Add demo app
20 | COPY ./app /app
21 | WORKDIR /app
22 |
23 | # Make /app/* available to be imported by Python globally to better support several use cases like Alembic migrations.
24 | ENV PYTHONPATH=/app
25 |
26 | # Move the base entrypoint to reuse it
27 | RUN mv /entrypoint.sh /uwsgi-nginx-entrypoint.sh
28 | # Copy the entrypoint that will generate Nginx additional configs
29 | COPY entrypoint.sh /entrypoint.sh
30 | RUN chmod +x /entrypoint.sh
31 |
32 | ENTRYPOINT ["/entrypoint.sh"]
33 |
34 | # Run the start script provided by the parent image tiangolo/uwsgi-nginx.
35 | # It will check for an /app/prestart.sh script (e.g. for migrations)
36 | # And then will start Supervisor, which in turn will start Nginx and uWSGI
37 | CMD ["/start.sh"]
38 |
--------------------------------------------------------------------------------
/scripts/process_all.py:
--------------------------------------------------------------------------------
1 | import os
2 | import subprocess
3 | import sys
4 |
5 | environments = [
6 | {"NAME": "latest", "PYTHON_VERSION": "3.12"},
7 | {"NAME": "python3.12", "PYTHON_VERSION": "3.12"},
8 | {"NAME": "python3.11", "PYTHON_VERSION": "3.11"},
9 | {"NAME": "python3.10", "PYTHON_VERSION": "3.10"},
10 | {"NAME": "python3.9", "PYTHON_VERSION": "3.9"},
11 | {"NAME": "python3.8", "PYTHON_VERSION": "3.8"},
12 | {"NAME": "python3.7", "PYTHON_VERSION": "3.7"},
13 | ]
14 |
15 | start_with = os.environ.get("START_WITH")
16 | build_push = os.environ.get("BUILD_PUSH")
17 |
18 |
19 | def process_tag(*, env: dict) -> None:
20 | use_env = {**os.environ, **env}
21 | script = "scripts/test.sh"
22 | if build_push:
23 | script = "scripts/build-push.sh"
24 | return_code = subprocess.call(["bash", script], env=use_env)
25 | if return_code != 0:
26 | sys.exit(return_code)
27 |
28 |
29 | def print_version_envs() -> None:
30 | env_lines = []
31 | for env in environments:
32 | env_vars = []
33 | for key, value in env.items():
34 | env_vars.append(f"{key}='{value}'")
35 | env_lines.append(" ".join(env_vars))
36 | for line in env_lines:
37 | print(line)
38 |
39 |
40 | def main() -> None:
41 | start_at = 0
42 | if start_with:
43 | start_at = [
44 | i for i, env in enumerate((environments)) if env["NAME"] == start_with
45 | ][0]
46 | for i, env in enumerate(environments[start_at:]):
47 | print(f"Processing tag: {env['NAME']}")
48 | process_tag(env=env)
49 |
50 |
51 | if __name__ == "__main__":
52 | if len(sys.argv) > 1:
53 | print_version_envs()
54 | else:
55 | main()
56 |
--------------------------------------------------------------------------------
/docker-images/entrypoint.sh:
--------------------------------------------------------------------------------
1 | #! /usr/bin/env sh
2 | set -e
3 |
4 | /uwsgi-nginx-entrypoint.sh
5 |
6 | # Get the URL for static files from the environment variable
7 | USE_STATIC_URL=${STATIC_URL:-'/static'}
8 | # Get the absolute path of the static files from the environment variable
9 | USE_STATIC_PATH=${STATIC_PATH:-'/app/static'}
10 | # Get the listen port for Nginx, default to 80
11 | USE_LISTEN_PORT=${LISTEN_PORT:-80}
12 |
13 | if [ -f /app/nginx.conf ]; then
14 | cp /app/nginx.conf /etc/nginx/nginx.conf
15 | else
16 | content_server='server {\n'
17 | content_server=$content_server" listen ${USE_LISTEN_PORT};\n"
18 | content_server=$content_server' location / {\n'
19 | content_server=$content_server' try_files $uri @app;\n'
20 | content_server=$content_server' }\n'
21 | content_server=$content_server' location @app {\n'
22 | content_server=$content_server' include uwsgi_params;\n'
23 | content_server=$content_server' uwsgi_pass unix:///tmp/uwsgi.sock;\n'
24 | content_server=$content_server' }\n'
25 | content_server=$content_server" location $USE_STATIC_URL {\n"
26 | content_server=$content_server" alias $USE_STATIC_PATH;\n"
27 | content_server=$content_server' }\n'
28 | # If STATIC_INDEX is 1, serve / with /static/index.html directly (or the static URL configured)
29 | if [ "$STATIC_INDEX" = 1 ] ; then
30 | content_server=$content_server' location = / {\n'
31 | content_server=$content_server" index $USE_STATIC_URL/index.html;\n"
32 | content_server=$content_server' }\n'
33 | fi
34 | content_server=$content_server'}\n'
35 | # Save generated server /etc/nginx/conf.d/nginx.conf
36 | printf "$content_server" > /etc/nginx/conf.d/nginx.conf
37 | fi
38 |
39 | exec "$@"
40 |
--------------------------------------------------------------------------------
/tests/utils.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 | from docker.client import DockerClient
4 | from docker.errors import NotFound
5 | from docker.models.containers import Container
6 |
7 | CONTAINER_NAME = "uwsgi-nginx-flask-test"
8 |
9 |
10 | def get_logs(container: Container) -> str:
11 | logs = container.logs()
12 | return logs.decode("utf-8")
13 |
14 |
15 | def get_nginx_config(container: Container) -> str:
16 | result = container.exec_run(f"/usr/sbin/nginx -T")
17 | return result.output.decode()
18 |
19 |
20 | def remove_previous_container(client: DockerClient) -> None:
21 | try:
22 | previous = client.containers.get(CONTAINER_NAME)
23 | previous.stop()
24 | previous.remove()
25 | except NotFound:
26 | return None
27 |
28 |
29 | def get_response_text1() -> str:
30 | python_version = os.getenv("PYTHON_VERSION")
31 | return f"Hello World from Flask in a uWSGI Nginx Docker container with Python {python_version} (default)"
32 |
33 |
34 | def get_response_text2() -> str:
35 | python_version = os.getenv("PYTHON_VERSION")
36 | return f"Hello World from Flask in a uWSGI Nginx Docker container with Python {python_version} - testing"
37 |
38 |
39 | def generate_dockerfile_content_custom_app(name: str) -> str:
40 | content = f"FROM tiangolo/uwsgi-nginx-flask:{name}\n"
41 | content += "COPY ./application /application\n"
42 | content += "COPY ./prestart.sh /app/prestart.sh\n"
43 | content += "WORKDIR /application\n"
44 | return content
45 |
46 |
47 | def generate_dockerfile_content_custom_nginx_app(name: str) -> str:
48 | content = f"FROM tiangolo/uwsgi-nginx-flask:{name}\n"
49 | content += "COPY app /app\n"
50 | return content
51 |
52 |
53 | def generate_dockerfile_content_simple_app(name: str) -> str:
54 | content = f"FROM tiangolo/uwsgi-nginx-flask:{name}\n"
55 | content += "COPY ./app/ /app/\n"
56 | return content
57 |
--------------------------------------------------------------------------------
/.github/workflows/test.yml:
--------------------------------------------------------------------------------
1 | name: Test
2 |
3 | on:
4 | push:
5 | branches:
6 | - master
7 | pull_request:
8 | types:
9 | - opened
10 | - synchronize
11 | schedule:
12 | # cron every week on monday
13 | - cron: "0 0 * * 1"
14 |
15 | jobs:
16 | test:
17 | strategy:
18 | matrix:
19 | image:
20 | - name: latest
21 | python_version: "3.12"
22 | - name: python3.12
23 | python_version: "3.12"
24 | - name: python3.11
25 | python_version: "3.11"
26 | - name: python3.10
27 | python_version: "3.10"
28 | - name: python3.9
29 | python_version: "3.9"
30 | fail-fast: true
31 | runs-on: ubuntu-latest
32 | steps:
33 | - uses: actions/checkout@v4
34 | - name: Set Dockerfile name
35 | if: matrix.image.name != 'latest'
36 | run: echo "DOCKERFILE_NAME=${{ matrix.image.name }}" >> $GITHUB_ENV
37 | - name: Set Dockerfile name latest
38 | if: matrix.image.name == 'latest'
39 | run: echo "DOCKERFILE_NAME=python${{ matrix.image.python_version }}" >> $GITHUB_ENV
40 | - name: Build
41 | uses: docker/build-push-action@v6
42 | with:
43 | push: false
44 | tags: tiangolo/uwsgi-nginx-flask:${{ matrix.image.name }}
45 | context: ./docker-images/
46 | file: ./docker-images/${{ env.DOCKERFILE_NAME }}.dockerfile
47 | - name: Set up Python
48 | uses: actions/setup-python@v5
49 | with:
50 | python-version: "3.10"
51 | - name: Install Dependencies
52 | run: python -m pip install docker pytest
53 | - name: Test Image
54 | run: bash scripts/test.sh
55 | env:
56 | NAME: ${{ matrix.image.name }}
57 | PYTHON_VERSION: ${{ matrix.image.python_version }}
58 | check:
59 | if: always()
60 | needs:
61 | - test
62 | runs-on: ubuntu-latest
63 | steps:
64 | - name: Decide whether the needed jobs succeeded or failed
65 | uses: re-actors/alls-green@release/v1
66 | with:
67 | jobs: ${{ toJSON(needs) }}
68 |
--------------------------------------------------------------------------------
/.github/workflows/deploy.yml:
--------------------------------------------------------------------------------
1 | name: Deploy
2 |
3 | on:
4 | push:
5 | branches:
6 | - master
7 | schedule:
8 | # cron every week on monday
9 | - cron: "0 0 * * 1"
10 |
11 | jobs:
12 | deploy:
13 | strategy:
14 | matrix:
15 | image:
16 | - name: latest
17 | python_version: "3.12"
18 | - name: python3.12
19 | python_version: "3.12"
20 | - name: python3.11
21 | python_version: "3.11"
22 | - name: python3.10
23 | python_version: "3.10"
24 | - name: python3.9
25 | python_version: "3.9"
26 | fail-fast: true
27 | runs-on: ubuntu-latest
28 | steps:
29 | - uses: actions/checkout@v4
30 | - name: Set Dockerfile name
31 | if: matrix.image.name != 'latest'
32 | run: echo "DOCKERFILE_NAME=${{ matrix.image.name }}" >> $GITHUB_ENV
33 | - name: Set Dockerfile name latest
34 | if: matrix.image.name == 'latest'
35 | run: echo "DOCKERFILE_NAME=python${{ matrix.image.python_version }}" >> $GITHUB_ENV
36 | - name: Set up Docker Buildx
37 | uses: docker/setup-buildx-action@v3
38 | - name: Login to DockerHub
39 | uses: docker/login-action@v3
40 | with:
41 | username: ${{ secrets.DOCKERHUB_USERNAME }}
42 | password: ${{ secrets.DOCKERHUB_TOKEN }}
43 | - name: Get date for tags
44 | run: echo "DATE_TAG=$(date -I)" >> "$GITHUB_ENV"
45 | - name: Build and push
46 | uses: docker/build-push-action@v6
47 | with:
48 | push: true
49 | platforms: linux/amd64,linux/arm64
50 | tags: |
51 | tiangolo/uwsgi-nginx-flask:${{ matrix.image.name }}
52 | tiangolo/uwsgi-nginx-flask:${{ matrix.image.name }}-${{ env.DATE_TAG }}
53 | context: ./docker-images/
54 | file: ./docker-images/${{ env.DOCKERFILE_NAME }}.dockerfile
55 | - name: Docker Hub Description
56 | uses: peter-evans/dockerhub-description@v4
57 | with:
58 | username: ${{ secrets.DOCKERHUB_USERNAME }}
59 | password: ${{ secrets.DOCKERHUB_TOKEN }}
60 | repository: tiangolo/uwsgi-nginx-flask
61 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ### Python template
2 | # Byte-compiled / optimized / DLL files
3 | __pycache__/
4 | *.py[cod]
5 | *$py.class
6 | .mypy_cache
7 | .vscode
8 |
9 | # C extensions
10 | *.so
11 |
12 | # Distribution / packaging
13 | .Python
14 | env/
15 | build/
16 | develop-eggs/
17 | dist/
18 | downloads/
19 | eggs/
20 | .eggs/
21 | lib/
22 | lib64/
23 | parts/
24 | sdist/
25 | var/
26 | *.egg-info/
27 | .installed.cfg
28 | *.egg
29 |
30 | # PyInstaller
31 | # Usually these files are written by a python script from a template
32 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
33 | *.manifest
34 | *.spec
35 |
36 | # Installer logs
37 | pip-log.txt
38 | pip-delete-this-directory.txt
39 |
40 | # Unit test / coverage reports
41 | htmlcov/
42 | .tox/
43 | .coverage
44 | .coverage.*
45 | .cache
46 | nosetests.xml
47 | coverage.xml
48 | *,cover
49 |
50 | # Translations
51 | *.mo
52 | *.pot
53 |
54 | # Django stuff:
55 | *.log
56 |
57 | # Sphinx documentation
58 | docs/_build/
59 |
60 | # PyBuilder
61 | target/
62 | ### JetBrains template
63 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio
64 |
65 | *.iml
66 |
67 | ## Directory-based project format:
68 | .idea/
69 | # if you remove the above rule, at least ignore the following:
70 |
71 | # User-specific stuff:
72 | # .idea/workspace.xml
73 | # .idea/tasks.xml
74 | # .idea/dictionaries
75 |
76 | # Sensitive or high-churn files:
77 | # .idea/dataSources.ids
78 | # .idea/dataSources.xml
79 | # .idea/sqlDataSources.xml
80 | # .idea/dynamic.xml
81 | # .idea/uiDesigner.xml
82 |
83 | # Gradle:
84 | # .idea/gradle.xml
85 | # .idea/libraries
86 |
87 | # Mongo Explorer plugin:
88 | # .idea/mongoSettings.xml
89 |
90 | ## File-based project format:
91 | *.ipr
92 | *.iws
93 |
94 | ## Plugin-specific files:
95 |
96 | # IntelliJ
97 | /out/
98 |
99 | # mpeltonen/sbt-idea plugin
100 | .idea_modules/
101 |
102 | # JIRA plugin
103 | atlassian-ide-plugin.xml
104 |
105 | # Crashlytics plugin (for Android Studio and IntelliJ)
106 | com_crashlytics_export_strings.xml
107 | crashlytics.properties
108 | crashlytics-build.properties
109 |
110 | # Custom
111 | Pipfile.lock
112 | poetry.lock
113 |
--------------------------------------------------------------------------------
/tests/test_01_main/test_defaults_01.py:
--------------------------------------------------------------------------------
1 | import os
2 | import time
3 |
4 | import docker
5 | import requests
6 | from docker.models.containers import Container
7 |
8 | from ..utils import (
9 | CONTAINER_NAME,
10 | get_logs,
11 | get_nginx_config,
12 | get_response_text1,
13 | remove_previous_container,
14 | )
15 |
16 | client = docker.from_env()
17 |
18 |
19 | def verify_container(container: Container, response_text: str) -> None:
20 | response = requests.get("http://127.0.0.1:8000")
21 | assert response.text == response_text
22 | nginx_config = get_nginx_config(container)
23 | assert "client_max_body_size 0;" in nginx_config
24 | assert "worker_processes 1;" in nginx_config
25 | assert "listen 80;" in nginx_config
26 | assert "worker_connections 1024;" in nginx_config
27 | assert "worker_rlimit_nofile;" not in nginx_config
28 | assert "daemon off;" in nginx_config
29 | assert "include uwsgi_params;" in nginx_config
30 | assert "uwsgi_pass unix:///tmp/uwsgi.sock;" in nginx_config
31 | assert "try_files $uri @app;" in nginx_config
32 | assert "location @app {" in nginx_config
33 | assert "include uwsgi_params;" in nginx_config
34 | assert "location /static {" in nginx_config
35 | assert "alias /app/static;" in nginx_config
36 | # Nginx index.html specific
37 | assert "location = / {" not in nginx_config
38 | assert "index /static/index.html;" not in nginx_config
39 | logs = get_logs(container)
40 | assert "getting INI configuration from /app/uwsgi.ini" in logs
41 | assert "getting INI configuration from /etc/uwsgi/uwsgi.ini" in logs
42 | assert "ini = /app/uwsgi.ini" in logs
43 | assert "ini = /etc/uwsgi/uwsgi.ini" in logs
44 | assert "socket = /tmp/uwsgi.sock" in logs
45 | assert "chown-socket = nginx:nginx" in logs
46 | assert "chmod-socket = 664" in logs
47 | assert "hook-master-start = unix_signal:15 gracefully_kill_them_all" in logs
48 | assert "need-app = true" in logs
49 | assert "die-on-term = true" in logs
50 | assert "show-config = true" in logs
51 | assert "module = main" in logs
52 | assert "callable = app" in logs
53 | assert "processes = 16" in logs
54 | assert "cheaper = 2" in logs
55 | assert "Checking for script in /app/prestart.sh" in logs
56 | assert "Running script /app/prestart.sh" in logs
57 | assert (
58 | "Running inside /app/prestart.sh, you could add migrations to this file" in logs
59 | )
60 | assert "spawned uWSGI master process" in logs
61 | assert "spawned uWSGI worker 1" in logs
62 | assert "spawned uWSGI worker 2" in logs
63 | assert "spawned uWSGI worker 3" not in logs
64 | assert 'running "unix_signal:15 gracefully_kill_them_all" (master-start)' in logs
65 | assert "success: nginx entered RUNNING state, process has stayed up for" in logs
66 | assert "success: uwsgi entered RUNNING state, process has stayed up for" in logs
67 |
68 |
69 | def test_defaults() -> None:
70 | name = os.getenv("NAME", "")
71 | # It's an index postfix tag, skip it
72 | image = f"tiangolo/uwsgi-nginx-flask:{name}"
73 | response_text = get_response_text1()
74 | sleep_time = int(os.getenv("SLEEP_TIME", 3))
75 | remove_previous_container(client)
76 | container = client.containers.run(
77 | image, name=CONTAINER_NAME, ports={"80": "8000"}, detach=True
78 | )
79 | time.sleep(sleep_time)
80 | verify_container(container, response_text)
81 | container.stop()
82 | # Test that everything works after restarting too
83 | container.start()
84 | time.sleep(sleep_time)
85 | verify_container(container, response_text)
86 | container.stop()
87 | container.remove()
88 |
--------------------------------------------------------------------------------
/tests/test_02_app/test_simple_app.py:
--------------------------------------------------------------------------------
1 | import os
2 | import time
3 | from pathlib import Path
4 |
5 | import docker
6 | import requests
7 | from docker.models.containers import Container
8 |
9 | from ..utils import (
10 | CONTAINER_NAME,
11 | generate_dockerfile_content_simple_app,
12 | get_logs,
13 | get_nginx_config,
14 | get_response_text2,
15 | remove_previous_container,
16 | )
17 |
18 | client = docker.from_env()
19 |
20 |
21 | def verify_container(container: Container, response_text: str) -> None:
22 | response = requests.get("http://127.0.0.1:8000")
23 | assert response.text == response_text
24 | response = requests.get("http://127.0.0.1:8000/static/test.txt")
25 | assert response.text == "Static test"
26 | nginx_config = get_nginx_config(container)
27 | assert "client_max_body_size 0;" in nginx_config
28 | assert "worker_processes 1;" in nginx_config
29 | assert "listen 80;" in nginx_config
30 | assert "worker_connections 1024;" in nginx_config
31 | assert "worker_rlimit_nofile;" not in nginx_config
32 | assert "daemon off;" in nginx_config
33 | assert "include uwsgi_params;" in nginx_config
34 | assert "uwsgi_pass unix:///tmp/uwsgi.sock;" in nginx_config
35 | assert "try_files $uri @app;" in nginx_config
36 | assert "location @app {" in nginx_config
37 | assert "include uwsgi_params;" in nginx_config
38 | assert "location /static {" in nginx_config
39 | assert "alias /app/static;" in nginx_config
40 | # Nginx index.html specific
41 | assert "location = / {" not in nginx_config
42 | assert "index /static/index.html;" not in nginx_config
43 | logs = get_logs(container)
44 | assert "getting INI configuration from /app/uwsgi.ini" in logs
45 | assert "getting INI configuration from /etc/uwsgi/uwsgi.ini" in logs
46 | assert "ini = /app/uwsgi.ini" in logs
47 | assert "ini = /etc/uwsgi/uwsgi.ini" in logs
48 | assert "socket = /tmp/uwsgi.sock" in logs
49 | assert "chown-socket = nginx:nginx" in logs
50 | assert "chmod-socket = 664" in logs
51 | assert "hook-master-start = unix_signal:15 gracefully_kill_them_all" in logs
52 | assert "need-app = true" in logs
53 | assert "die-on-term = true" in logs
54 | assert "show-config = true" in logs
55 | assert "module = main" in logs
56 | assert "callable = app" in logs
57 | assert "processes = 16" in logs
58 | assert "cheaper = 2" in logs
59 | assert "Checking for script in /app/prestart.sh" in logs
60 | assert "Running script /app/prestart.sh" in logs
61 | assert (
62 | "Running inside /app/prestart.sh, you could add migrations to this file" in logs
63 | )
64 | assert "spawned uWSGI master process" in logs
65 | assert "spawned uWSGI worker 1" in logs
66 | assert "spawned uWSGI worker 2" in logs
67 | assert "spawned uWSGI worker 3" not in logs
68 | assert 'running "unix_signal:15 gracefully_kill_them_all" (master-start)' in logs
69 | assert "success: nginx entered RUNNING state, process has stayed up for" in logs
70 | assert "success: uwsgi entered RUNNING state, process has stayed up for" in logs
71 |
72 |
73 | def test_env_vars_1() -> None:
74 | name = os.getenv("NAME", "")
75 | dockerfile_content = generate_dockerfile_content_simple_app(name)
76 | dockerfile = "Dockerfile"
77 | response_text = get_response_text2()
78 | sleep_time = int(os.getenv("SLEEP_TIME", 3))
79 | remove_previous_container(client)
80 | tag = "uwsgi-nginx-flask-testimage"
81 | test_path = Path(__file__)
82 | path = test_path.parent / "simple_app"
83 | dockerfile_path = path / dockerfile
84 | dockerfile_path.write_text(dockerfile_content)
85 | client.images.build(path=str(path), dockerfile=dockerfile, tag=tag)
86 | container = client.containers.run(
87 | tag, name=CONTAINER_NAME, ports={"80": "8000"}, detach=True
88 | )
89 | time.sleep(sleep_time)
90 | verify_container(container, response_text)
91 | container.stop()
92 | # Test that everything works after restarting too
93 | container.start()
94 | time.sleep(sleep_time)
95 | verify_container(container, response_text)
96 | container.stop()
97 | container.remove()
98 |
--------------------------------------------------------------------------------
/tests/test_02_app/test_custom_ngnix_app.py:
--------------------------------------------------------------------------------
1 | import os
2 | import time
3 | from pathlib import Path
4 |
5 | import docker
6 | import requests
7 | from docker.models.containers import Container
8 |
9 | from ..utils import (
10 | CONTAINER_NAME,
11 | generate_dockerfile_content_custom_nginx_app,
12 | get_logs,
13 | get_nginx_config,
14 | get_response_text2,
15 | remove_previous_container,
16 | )
17 |
18 | client = docker.from_env()
19 |
20 |
21 | def verify_container(container: Container, response_text: str) -> None:
22 | response = requests.get("http://127.0.0.1:8080")
23 | assert response.text == response_text
24 | response = requests.get("http://127.0.0.1:8080/static/test.txt")
25 | assert response.text == "Static, from Flask"
26 | nginx_config = get_nginx_config(container)
27 | assert "client_max_body_size 0;" not in nginx_config
28 | assert "worker_processes 2;" in nginx_config
29 | assert "listen 8080;" in nginx_config
30 | assert "worker_connections 2048;" in nginx_config
31 | assert "worker_rlimit_nofile;" not in nginx_config
32 | assert "daemon off;" in nginx_config
33 | assert "include uwsgi_params;" in nginx_config
34 | assert "uwsgi_pass unix:///tmp/uwsgi.sock;" in nginx_config
35 | assert "try_files $uri @app;" in nginx_config
36 | assert "location @app {" in nginx_config
37 | assert "include uwsgi_params;" in nginx_config
38 | assert "location /static {" not in nginx_config
39 | assert "alias /app/static;" not in nginx_config
40 | # Nginx index.html specific
41 | assert "location = / {" not in nginx_config
42 | assert "index /static/index.html;" not in nginx_config
43 | logs = get_logs(container)
44 | assert "getting INI configuration from /app/uwsgi.ini" in logs
45 | assert "getting INI configuration from /etc/uwsgi/uwsgi.ini" in logs
46 | assert "ini = /app/uwsgi.ini" in logs
47 | assert "ini = /etc/uwsgi/uwsgi.ini" in logs
48 | assert "socket = /tmp/uwsgi.sock" in logs
49 | assert "chown-socket = nginx:nginx" in logs
50 | assert "chmod-socket = 664" in logs
51 | assert "hook-master-start = unix_signal:15 gracefully_kill_them_all" in logs
52 | assert "need-app = true" in logs
53 | assert "die-on-term = true" in logs
54 | assert "show-config = true" in logs
55 | assert "module = main" in logs
56 | assert "callable = app" in logs
57 | assert "processes = 16" in logs
58 | assert "cheaper = 2" in logs
59 | assert "Checking for script in /app/prestart.sh" in logs
60 | assert "Running script /app/prestart.sh" in logs
61 | assert (
62 | "Running inside /app/prestart.sh, you could add migrations to this file" in logs
63 | )
64 | assert "spawned uWSGI master process" in logs
65 | assert "spawned uWSGI worker 1" in logs
66 | assert "spawned uWSGI worker 2" in logs
67 | assert "spawned uWSGI worker 3" not in logs
68 | assert 'running "unix_signal:15 gracefully_kill_them_all" (master-start)' in logs
69 | assert "success: nginx entered RUNNING state, process has stayed up for" in logs
70 | assert "success: uwsgi entered RUNNING state, process has stayed up for" in logs
71 |
72 |
73 | def test_env_vars_1() -> None:
74 | name = os.getenv("NAME", "")
75 | dockerfile_content = generate_dockerfile_content_custom_nginx_app(name)
76 | dockerfile = "Dockerfile"
77 | response_text = get_response_text2()
78 | sleep_time = int(os.getenv("SLEEP_TIME", 3))
79 | remove_previous_container(client)
80 | tag = "uwsgi-nginx-flask-testimage"
81 | test_path = Path(__file__)
82 | path = test_path.parent / "custom_nginx_app"
83 | dockerfile_path = path / dockerfile
84 | dockerfile_path.write_text(dockerfile_content)
85 | client.images.build(path=str(path), dockerfile=dockerfile, tag=tag)
86 | container = client.containers.run(
87 | tag, name=CONTAINER_NAME, ports={"8080": "8080"}, detach=True
88 | )
89 | time.sleep(sleep_time)
90 | verify_container(container, response_text)
91 | container.stop()
92 | # Test that everything works after restarting too
93 | container.start()
94 | time.sleep(sleep_time)
95 | verify_container(container, response_text)
96 | container.stop()
97 | container.remove()
98 |
--------------------------------------------------------------------------------
/tests/test_01_main/test_env_vars_03.py:
--------------------------------------------------------------------------------
1 | import os
2 | import time
3 |
4 | import docker
5 | import requests
6 | from docker.models.containers import Container
7 | from requests import Response
8 |
9 | from ..utils import (
10 | CONTAINER_NAME,
11 | get_logs,
12 | get_nginx_config,
13 | get_response_text1,
14 | remove_previous_container,
15 | )
16 |
17 | client = docker.from_env()
18 |
19 |
20 | def verify_container(container: Container, response_text: str) -> None:
21 | nginx_config = get_nginx_config(container)
22 | assert "client_max_body_size 1m;" in nginx_config
23 | assert "worker_processes 2;" in nginx_config
24 | assert "listen 80;" in nginx_config
25 | assert "worker_connections 2048;" in nginx_config
26 | assert "worker_rlimit_nofile 2048;" in nginx_config
27 | assert "daemon off;" in nginx_config
28 | assert "listen 80;" in nginx_config
29 | assert "include uwsgi_params;" in nginx_config
30 | assert "uwsgi_pass unix:///tmp/uwsgi.sock;" in nginx_config
31 | assert "try_files $uri @app;" in nginx_config
32 | assert "location @app {" in nginx_config
33 | assert "include uwsgi_params;" in nginx_config
34 | assert "location /static {" in nginx_config
35 | assert "alias /app/static;" in nginx_config
36 | # Nginx index.html specific
37 | assert "location = / {" not in nginx_config
38 | assert "index /static/index.html;" not in nginx_config
39 | logs = get_logs(container)
40 | assert "getting INI configuration from /app/uwsgi.ini" in logs
41 | assert "getting INI configuration from /etc/uwsgi/uwsgi.ini" in logs
42 | assert "ini = /app/uwsgi.ini" in logs
43 | assert "ini = /etc/uwsgi/uwsgi.ini" in logs
44 | assert "socket = /tmp/uwsgi.sock" in logs
45 | assert "chown-socket = nginx:nginx" in logs
46 | assert "chmod-socket = 664" in logs
47 | assert "hook-master-start = unix_signal:15 gracefully_kill_them_all" in logs
48 | assert "need-app = true" in logs
49 | assert "die-on-term = true" in logs
50 | assert "show-config = true" in logs
51 | assert "module = main" in logs
52 | assert "callable = app" in logs
53 | assert "processes = 8" in logs
54 | assert "cheaper = 3" in logs
55 | assert "spawned uWSGI master process" in logs
56 | assert "spawned uWSGI worker 1" in logs
57 | assert "spawned uWSGI worker 2" in logs
58 | assert "spawned uWSGI worker 3" in logs
59 | assert "spawned uWSGI worker 4" not in logs
60 | assert 'running "unix_signal:15 gracefully_kill_them_all" (master-start)' in logs
61 | assert "success: nginx entered RUNNING state, process has stayed up for" in logs
62 | assert "success: uwsgi entered RUNNING state, process has stayed up for" in logs
63 | assert "Checking for script in /app/prestart.sh" in logs
64 | assert "Running script /app/prestart.sh" in logs
65 | assert (
66 | "Running inside /app/prestart.sh, you could add migrations to this file" in logs
67 | )
68 | response: Response = requests.get("http://127.0.0.1:8000")
69 | assert response.status_code == 200
70 | assert response.text == response_text
71 |
72 |
73 | def test_defaults() -> None:
74 |
75 | name = os.getenv("NAME", "")
76 | image = f"tiangolo/uwsgi-nginx-flask:{name}"
77 | response_text = get_response_text1()
78 | sleep_time = int(os.getenv("SLEEP_TIME", 3))
79 | remove_previous_container(client)
80 | container = client.containers.run(
81 | image,
82 | name=CONTAINER_NAME,
83 | environment={
84 | "UWSGI_CHEAPER": 3,
85 | "UWSGI_PROCESSES": 8,
86 | "NGINX_MAX_UPLOAD": "1m",
87 | "NGINX_WORKER_PROCESSES": 2,
88 | "NGINX_WORKER_CONNECTIONS": 2048,
89 | "NGINX_WORKER_OPEN_FILES": 2048,
90 | },
91 | ports={"80": "8000"},
92 | detach=True,
93 | )
94 | time.sleep(sleep_time)
95 | verify_container(container, response_text)
96 | container.stop()
97 | # Test that everything works after restarting too
98 | container.start()
99 | time.sleep(sleep_time)
100 | verify_container(container, response_text)
101 | container.stop()
102 | container.remove()
103 |
--------------------------------------------------------------------------------
/tests/test_02_app/test_app_and_env_vars.py:
--------------------------------------------------------------------------------
1 | import os
2 | import time
3 | from pathlib import Path
4 |
5 | import docker
6 | import requests
7 | from docker.models.containers import Container
8 |
9 | from ..utils import (
10 | CONTAINER_NAME,
11 | generate_dockerfile_content_custom_app,
12 | get_logs,
13 | get_nginx_config,
14 | get_response_text2,
15 | remove_previous_container,
16 | )
17 |
18 | client = docker.from_env()
19 |
20 |
21 | def verify_container(container: Container, response_text: str) -> None:
22 | response = requests.get("http://127.0.0.1:8000")
23 | assert (
24 | response.text == "Hello World from HTML test
"
25 | )
26 | response = requests.get("http://127.0.0.1:8000/api")
27 | assert response.text == response_text
28 | response = requests.get("http://127.0.0.1:8000/content/test.txt")
29 | assert response.text == "Static test"
30 | nginx_config = get_nginx_config(container)
31 | assert "client_max_body_size 0;" in nginx_config
32 | assert "worker_processes 1;" in nginx_config
33 | assert "listen 8080;" in nginx_config
34 | assert "worker_connections 1024;" in nginx_config
35 | assert "worker_rlimit_nofile;" not in nginx_config
36 | assert "daemon off;" in nginx_config
37 | assert "include uwsgi_params;" in nginx_config
38 | assert "uwsgi_pass unix:///tmp/uwsgi.sock;" in nginx_config
39 | # Nginx index.html specific
40 | assert "location /content {" in nginx_config
41 | assert "index /content/index.html;" in nginx_config
42 | assert "location = / {" in nginx_config
43 | assert "alias /application/custom_app/content;" in nginx_config
44 | logs = get_logs(container)
45 | assert "getting INI configuration from /application/custom_app/uwsgi.ini" in logs
46 | assert "getting INI configuration from /etc/uwsgi/uwsgi.ini" in logs
47 | assert "ini = /application/custom_app/uwsgi.ini" in logs
48 | assert "ini = /etc/uwsgi/uwsgi.ini" in logs
49 | assert "socket = /tmp/uwsgi.sock" in logs
50 | assert "chown-socket = nginx:nginx" in logs
51 | assert "chmod-socket = 664" in logs
52 | assert "hook-master-start = unix_signal:15 gracefully_kill_them_all" in logs
53 | assert "need-app = true" in logs
54 | assert "die-on-term = true" in logs
55 | assert "show-config = true" in logs
56 | assert "module = custom_app.main" in logs
57 | assert "callable = custom_app" in logs
58 | assert "processes = 16" in logs
59 | assert "cheaper = 2" in logs
60 | assert "Checking for script in /app/prestart.sh" in logs
61 | assert "Running script /app/prestart.sh" in logs
62 | assert "custom prestart.sh running" in logs
63 | assert "spawned uWSGI master process" in logs
64 | assert "spawned uWSGI worker 1" in logs
65 | assert "spawned uWSGI worker 2" in logs
66 | assert "spawned uWSGI worker 3" not in logs
67 | assert 'running "unix_signal:15 gracefully_kill_them_all" (master-start)' in logs
68 | assert "success: nginx entered RUNNING state, process has stayed up for" in logs
69 | assert "success: uwsgi entered RUNNING state, process has stayed up for" in logs
70 |
71 |
72 | def test_env_vars_1() -> None:
73 | name = os.getenv("NAME", "")
74 | # It's an index postfix tag, skip it
75 | if "index" in name:
76 | return
77 | dockerfile_content = generate_dockerfile_content_custom_app(name)
78 | dockerfile = "Dockerfile"
79 | response_text = get_response_text2()
80 | sleep_time = int(os.getenv("SLEEP_TIME", 3))
81 | remove_previous_container(client)
82 | tag = "uwsgi-nginx-flask-testimage"
83 | test_path = Path(__file__)
84 | path = test_path.parent / "custom_app"
85 | dockerfile_path = path / dockerfile
86 | dockerfile_path.write_text(dockerfile_content)
87 | client.images.build(path=str(path), dockerfile=dockerfile, tag=tag)
88 | container = client.containers.run(
89 | tag,
90 | name=CONTAINER_NAME,
91 | environment={
92 | "UWSGI_INI": "/application/custom_app/uwsgi.ini",
93 | "LISTEN_PORT": "8080",
94 | "STATIC_URL": "/content",
95 | "STATIC_PATH": "/application/custom_app/content",
96 | "STATIC_INDEX": 1,
97 | },
98 | ports={"8080": "8000"},
99 | detach=True,
100 | )
101 | time.sleep(sleep_time)
102 | verify_container(container, response_text)
103 | container.stop()
104 | # Test that everything works after restarting too
105 | container.start()
106 | time.sleep(sleep_time)
107 | verify_container(container, response_text)
108 | container.stop()
109 | container.remove()
110 |
--------------------------------------------------------------------------------
/.github/DISCUSSION_TEMPLATE/questions.yml:
--------------------------------------------------------------------------------
1 | labels: [question]
2 | body:
3 | - type: markdown
4 | attributes:
5 | value: |
6 | Thanks for your interest in this project! 🚀
7 |
8 | Please follow these instructions, fill every question, and do every step. 🙏
9 |
10 | I'm asking this because answering questions and solving problems in GitHub is what consumes most of the time.
11 |
12 | I end up not being able to add new features, fix bugs, review pull requests, etc. as fast as I wish because I have to spend too much time handling questions.
13 |
14 | All that, on top of all the incredible help provided by a bunch of community members, that give a lot of their time to come here and help others.
15 |
16 | That's a lot of work, but if more users came to help others like them just a little bit more, it would be much less effort for them (and you and me 😅).
17 |
18 | By asking questions in a structured way (following this) it will be much easier to help you.
19 |
20 | And there's a high chance that you will find the solution along the way and you won't even have to submit it and wait for an answer. 😎
21 |
22 | As there are too many questions, I'll have to discard and close the incomplete ones. That will allow me (and others) to focus on helping people like you that follow the whole process and help us help you. 🤓
23 | - type: checkboxes
24 | id: checks
25 | attributes:
26 | label: First Check
27 | description: Please confirm and check all the following options.
28 | options:
29 | - label: I added a very descriptive title here.
30 | required: true
31 | - label: I used the GitHub search to find a similar question and didn't find it.
32 | required: true
33 | - label: I searched in the documentation/README.
34 | required: true
35 | - label: I already searched in Google "How to do X" and didn't find any information.
36 | required: true
37 | - label: I already read and followed all the tutorial in the docs/README and didn't find an answer.
38 | required: true
39 | - type: checkboxes
40 | id: help
41 | attributes:
42 | label: Commit to Help
43 | description: |
44 | After submitting this, I commit to one of:
45 |
46 | * Read open questions until I find 2 where I can help someone and add a comment to help there.
47 | * I already hit the "watch" button in this repository to receive notifications and I commit to help at least 2 people that ask questions in the future.
48 |
49 | options:
50 | - label: I commit to help with one of those options 👆
51 | required: true
52 | - type: textarea
53 | id: example
54 | attributes:
55 | label: Example Code
56 | description: |
57 | Please add a self-contained, [minimal, reproducible, example](https://stackoverflow.com/help/minimal-reproducible-example) with your use case.
58 |
59 | If I (or someone) can copy it, run it, and see it right away, there's a much higher chance I (or someone) will be able to help you.
60 |
61 | placeholder: |
62 | Write your example code here.
63 | render: Text
64 | validations:
65 | required: true
66 | - type: textarea
67 | id: description
68 | attributes:
69 | label: Description
70 | description: |
71 | What is the problem, question, or error?
72 |
73 | Write a short description telling me what you are doing, what you expect to happen, and what is currently happening.
74 | placeholder: |
75 | * Open the browser and call the endpoint `/`.
76 | * It returns a JSON with `{"message": "Hello World"}`.
77 | * But I expected it to return `{"message": "Hello Morty"}`.
78 | validations:
79 | required: true
80 | - type: dropdown
81 | id: os
82 | attributes:
83 | label: Operating System
84 | description: What operating system are you on?
85 | multiple: true
86 | options:
87 | - Linux
88 | - Windows
89 | - macOS
90 | - Other
91 | validations:
92 | required: true
93 | - type: textarea
94 | id: os-details
95 | attributes:
96 | label: Operating System Details
97 | description: You can add more details about your operating system here, in particular if you chose "Other".
98 | validations:
99 | required: true
100 | - type: input
101 | id: python-version
102 | attributes:
103 | label: Python Version
104 | description: |
105 | What Python version are you using?
106 |
107 | You can find the Python version with:
108 |
109 | ```bash
110 | python --version
111 | ```
112 | validations:
113 | required: true
114 | - type: textarea
115 | id: context
116 | attributes:
117 | label: Additional Context
118 | description: Add any additional context information or screenshots you think are useful.
119 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://github.com/tiangolo/uwsgi-nginx-flask-docker/actions/workflows/test.yml) [](https://github.com/tiangolo/uwsgi-nginx-flask-docker/actions?query=workflow%3ADeploy)
2 |
3 | ## Supported tags and respective `Dockerfile` links
4 |
5 | * [`python3.12`, `latest` _(Dockerfile)_](https://github.com/tiangolo/uwsgi-nginx-flask-docker/blob/master/docker-images/python3.12.dockerfile)
6 | * [`python3.11`, _(Dockerfile)_](https://github.com/tiangolo/uwsgi-nginx-flask-docker/blob/master/docker-images/python3.11.dockerfile)
7 | * [`python3.10` _(Dockerfile)_](https://github.com/tiangolo/uwsgi-nginx-flask-docker/blob/master/docker-images/python3.10.dockerfile)
8 | * [`python3.9`, _(Dockerfile)_](https://github.com/tiangolo/uwsgi-nginx-flask-docker/blob/master/docker-images/python3.9.dockerfile)
9 |
10 | ## Deprecated tags
11 |
12 | 🚨 These tags are no longer supported or maintained, they are removed from the GitHub repository, but the last versions pushed might still be available in Docker Hub if anyone has been pulling them:
13 |
14 | * `python3.8`
15 | * `python3.8-alpine`
16 | * `python3.7`
17 | * `python3.6`
18 | * `python2.7`
19 |
20 | The last date tags for these versions are:
21 |
22 | * `python3.8-2024-10-28`
23 | * `python3.8-alpine-2024-03-11`
24 | * `python3.7-2024-10-28`
25 | * `python3.6-2022-11-25`
26 | * `python2.7-2022-11-25`
27 |
28 | ---
29 |
30 | **Note**: There are [tags for each build date](https://hub.docker.com/r/tiangolo/uwsgi-nginx-flask/tags). If you need to "pin" the Docker image version you use, you can select one of those tags. E.g. `tiangolo/uwsgi-nginx-flask:python3.7-2019-10-14`.
31 |
32 | # uwsgi-nginx-flask
33 |
34 | **Docker** image with **uWSGI** and **Nginx** for **Flask** web applications in **Python** running in a single container.
35 |
36 | ## Description
37 |
38 | This [**Docker**](https://www.docker.com/) image allows you to create [**Flask**](http://flask.pocoo.org/) web applications in [**Python**](https://www.python.org/) that run with [**uWSGI**](https://uwsgi-docs.readthedocs.org/en/latest/) and [**Nginx**](http://nginx.org/en/) in a single container.
39 |
40 | The combination of uWSGI with Nginx is a [common way to deploy Python Flask web applications](http://flask.pocoo.org/docs/1.0/deploying/uwsgi/).
41 |
42 | ### Alternative - FastAPI
43 |
44 | If you are starting a new project, you might want to try [**FastAPI**](https://github.com/tiangolo/fastapi), which I created, and where I spend most of my time now. It also doesn't need a custom base image, there are instructions in the docs to build your own `Dockerfile`.
45 |
46 | ---
47 |
48 | **GitHub repo**: [https://github.com/tiangolo/uwsgi-nginx-flask-docker](https://github.com/tiangolo/uwsgi-nginx-flask-docker)
49 |
50 | **Docker Hub image**: [https://hub.docker.com/r/tiangolo/uwsgi-nginx-flask/](https://hub.docker.com/r/tiangolo/uwsgi-nginx-flask/)
51 |
52 | ## 🚨 WARNING: You Probably Don't Need this Docker Image
53 |
54 | You are probably using **Kubernetes** or similar tools. In that case, you probably **don't need this image** (or any other **similar base image**). You are probably better off **building a Docker image from scratch**.
55 |
56 | ---
57 |
58 | If you have a cluster of machines with **Kubernetes**, Docker Swarm Mode, Nomad, or other similar complex system to manage distributed containers on multiple machines, then you will probably want to **handle replication** at the **cluster level** instead of using a **process manager** in each container that starts multiple **worker processes**, which is what this Docker image does.
59 |
60 | In those cases (e.g. using Kubernetes) you would probably want to build a **Docker image from scratch**, installing your dependencies, and running **a single process** instead of this image.
61 |
62 | For example, using [Gunicorn](https://gunicorn.org/) you could have a file `app/gunicorn_conf.py` with:
63 |
64 | ```Python
65 | # Gunicorn config variables
66 | loglevel = "info"
67 | errorlog = "-" # stderr
68 | accesslog = "-" # stdout
69 | worker_tmp_dir = "/dev/shm"
70 | graceful_timeout = 120
71 | timeout = 120
72 | keepalive = 5
73 | threads = 3
74 | ```
75 |
76 | And then you could have a `Dockerfile` with:
77 |
78 | ```Dockerfile
79 | FROM python:3.12
80 |
81 | WORKDIR /code
82 |
83 | COPY ./requirements.txt /code/requirements.txt
84 |
85 | RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
86 |
87 | COPY ./app /code/app
88 |
89 | CMD ["gunicorn", "--conf", "app/gunicorn_conf.py", "--bind", "0.0.0.0:80", "app.main:app"]
90 | ```
91 |
92 | You can read more about these ideas in the [FastAPI documentation about: FastAPI in Containers - Docker](https://fastapi.tiangolo.com/deployment/docker/#replication-number-of-processes) as the same ideas would apply to other web applications in containers.
93 |
94 | ## When to Use this Docker Image
95 |
96 | ### A Simple App
97 |
98 | You could want a process manager running multiple worker processes in the container if your application is **simple enough** that you don't need (at least not yet) to fine-tune the number of processes too much, and you can just use an automated default, and you are running it on a **single server**, not a cluster.
99 |
100 | ### Docker Compose
101 |
102 | You could be deploying to a **single server** (not a cluster) with **Docker Compose**, so you wouldn't have an easy way to manage replication of containers (with Docker Compose) while preserving the shared network and **load balancing**.
103 |
104 | Then you could want to have **a single container** with a **process manager** starting **several worker processes** inside, as this Docker image does.
105 |
106 | ### Other Reasons
107 |
108 | You could also have **other reasons** that would make it easier to have a **single container** with **multiple processes** instead of having **multiple containers** with **a single process** in each of them.
109 |
110 | For example (depending on your setup) you could have some tool like a Prometheus exporter in the same container that should have access to **each of the requests** that come.
111 |
112 | In this case, if you had **multiple containers**, by default, when Prometheus came to **read the metrics**, it would get the ones for **a single container each time** (for the container that handled that particular request), instead of getting the **accumulated metrics** for all the replicated containers.
113 |
114 | Then, in that case, it could be simpler to have **one container** with **multiple processes**, and a local tool (e.g. a Prometheus exporter) on the same container collecting Prometheus metrics for all the internal processes and exposing those metrics on that single container.
115 |
116 | ---
117 |
118 | Read more about it all in the [FastAPI documentation about: FastAPI in Containers - Docker](https://fastapi.tiangolo.com/deployment/docker/), as the same concepts apply to other web applications in containers.
119 |
120 | ## General Instructions
121 |
122 | You don't have to clone this repo.
123 |
124 | You can use this image as a base image for other images.
125 |
126 | Assuming you have a file `requirements.txt`, you could have a `Dockerfile` like this:
127 |
128 | ```Dockerfile
129 | FROM tiangolo/uwsgi-nginx-flask:python3.12
130 |
131 | COPY ./requirements.txt /app/requirements.txt
132 |
133 | RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt
134 |
135 | COPY ./app /app
136 | ```
137 |
138 | There are several image tags available but for new projects you should use the latest version available.
139 |
140 | This Docker image is based on [**tiangolo/uwsgi-nginx**](https://hub.docker.com/r/tiangolo/uwsgi-nginx/). That Docker image has uWSGI and Nginx installed in the same container and was made to be the base of this image.
141 |
142 | ## Quick Start
143 |
144 | * Go to your project directory
145 | * Create a `Dockerfile` with:
146 |
147 | ```Dockerfile
148 | FROM tiangolo/uwsgi-nginx-flask:python3.12
149 |
150 | COPY ./app /app
151 | ```
152 |
153 | * Create an `app` directory and enter in it
154 | * Create a `main.py` file (it should be named like that and should be in your `app` directory) with:
155 |
156 | ```python
157 | from flask import Flask
158 | app = Flask(__name__)
159 |
160 | @app.route("/")
161 | def hello():
162 | return "Hello World from Flask"
163 |
164 | if __name__ == "__main__":
165 | # Only for debugging while developing
166 | app.run(host='0.0.0.0', debug=True, port=80)
167 | ```
168 |
169 | the main application object should be named `app` (in the code) as in this example.
170 |
171 | **Note**: The section with the `main()` function is for debugging purposes. To learn more, read the **Advanced instructions** below.
172 |
173 | * You should now have a directory structure like:
174 |
175 | ```
176 | .
177 | ├── app
178 | │ └── main.py
179 | └── Dockerfile
180 | ```
181 |
182 | * Go to the project directory (in where your `Dockerfile` is, containing your `app` directory)
183 | * Build your Flask image:
184 |
185 | ```bash
186 | docker build -t myimage .
187 | ```
188 |
189 | * Run a container based on your image:
190 |
191 | ```bash
192 | docker run -d --name mycontainer -p 80:80 myimage
193 | ```
194 |
195 | ...and you have an optimized Flask server in a Docker container.
196 |
197 | You should be able to check it in your Docker container's URL, for example: http://192.168.99.100 or http://127.0.0.1
198 |
199 | ## Quick Start for SPAs *
200 |
201 | ### Modern Single Page Applications
202 |
203 | If you are building modern frontend applications (e.g. [Vue](https://vuejs.org/), [React](https://reactjs.org/), [Angular](https://angular.io/)) you would most probably be compiling a modern version of JavaScript (ES2015, TypeScript, etc) to a less modern, more compatible version.
204 |
205 | If you want to serve your (compiled) frontend code by the same backend (Flask) Docker container, you would have to copy the code to the container after compiling it.
206 |
207 | That means that you would need to have all the frontend tools installed on the building machine (it might be your computer, a remote server, etc).
208 |
209 | That also means that you would have to, somehow, always remember to compile the frontend code right before building the Docker image.
210 |
211 | And it might also mean that you could then have to add your compiled frontend code to your `git` repository (hopefully you are using Git already, or [learning how to use `git`](https://www.atlassian.com/git)).
212 |
213 | Adding your compiled code to Git is a very bad idea for several reasons, some of those are:
214 |
215 | * You don't have a single, ultimate source of truth (the source code).
216 | * The compiled code might be stale, even when your source code is new, which might make you spend a lot of time debugging.
217 | * You might run into a lot of code conflicts when interacting with multiple team members with different Git branches, and spend a lot of time solving irrelevant code conflicts in the compiled code.
218 | * This might also ruin automatic branch merging in pull requests from other team members.
219 |
220 | For these reasons, it is not recommended that you serve your frontend code from the same backend (Flask) Docker container.
221 |
222 | ### Better alternative
223 |
224 | There's a much better alternative to serving your frontend code from the same backend (Flask) Docker container.
225 |
226 | You can have another Docker container with all the frontend tools installed (Node.js, etc) that:
227 |
228 | * Takes your source frontend code.
229 | * Compiles it and generates the final "distributable" frontend.
230 | * Uses Docker "multi-stage builds" to copy that compiled code into a pure Nginx Docker image.
231 | * The final frontend image only contains the compiled frontend code, directly from the source, but has the small size of an Nginx image, with all the performance from Nginx.
232 |
233 | To learn the specifics of this process for the frontend building in Docker you can read:
234 |
235 | * [React in Docker with Nginx, built with multi-stage Docker builds, including testing](https://medium.com/@tiangolo/react-in-docker-with-nginx-built-with-multi-stage-docker-builds-including-testing-8cc49d6ec305)
236 | * [Angular in Docker with Nginx, supporting configurations / environments, built with multi-stage Docker builds and testing with Chrome Headless](https://medium.com/@tiangolo/angular-in-docker-with-nginx-supporting-environments-built-with-multi-stage-docker-builds-bb9f1724e984)
237 |
238 | After having one backend (Flask) container and one frontend container, you need to serve both of them.
239 |
240 | And you might want to serve them under the same domain, under a different path. For example, the backend (Flask) app at the path `/api` and the frontend at the "root" path `/`.
241 |
242 | You can then use [Traefik](https://traefik.io/) to handle that.
243 |
244 | And it can also automatically generate HTTPS certificates for your application using Let's Encrypt. All for free, in a very easy setup.
245 |
246 | If you want to use this alternative, [check the project generators above](#project-generators), they all use this idea.
247 |
248 | In this scenario, you would have 3 Docker containers:
249 |
250 | * Backend (Flask)
251 | * Frontend (Vue.js, Angular, React or any other)
252 | * Traefik (load balancer, HTTPS)
253 |
254 | ## Quick Start for bigger projects structured as a Python package
255 |
256 | You should be able to follow the same instructions as in the "**QuickStart**" section above, with some minor modifications:
257 |
258 | * Instead of putting your code in the `app/` directory, put it in a directory `app/app/`.
259 | * Add an empty file `__init__.py` inside of that `app/app/` directory.
260 | * Add a file `uwsgi.ini` inside your `app/` directory (that is copied to `/app/uwsgi.ini` inside the container).
261 | * In your `uwsgi.ini` file, add:
262 |
263 | ```ini
264 | [uwsgi]
265 | module = app.main
266 | callable = app
267 | ```
268 |
269 | The explanation of the `uwsgi.ini` is as follows:
270 |
271 | * The module in where my Python web app lives is `app.main`. So, in the package `app` (`/app/app`), get the `main` module (`main.py`).
272 | * The Flask web application is the `app` object (`app = Flask(__name__)`).
273 |
274 | Your file structure would look like:
275 |
276 | ```
277 | .
278 | ├── app
279 | │ ├── app
280 | │ │ ├── __init__.py
281 | │ │ ├── main.py
282 | │ └── uwsgi.ini
283 | └── Dockerfile
284 | ```
285 |
286 | ...instead of:
287 |
288 | ```
289 | .
290 | ├── app
291 | │ ├── main.py
292 | └── Dockerfile
293 | ```
294 |
295 | If you are using static files in the same container, make sure the `STATIC_PATH` environment variable is set accordingly, for example to change the default value of `/app/static` to `/app/app/static` you could add this line to your `Dockerfile`:
296 |
297 | ```Dockerfile
298 | ENV STATIC_PATH /app/app/static
299 | ```
300 |
301 | ...after that, everything should work as expected. All the other instructions would apply normally.
302 |
303 | ### Working with submodules
304 |
305 | * After adding all your modules you could end up with a file structure similar to (taken from the example project):
306 |
307 | ```
308 | .
309 | ├── app
310 | │ ├── app
311 | │ │ ├── api
312 | │ │ │ ├── api.py
313 | │ │ │ ├── endpoints
314 | │ │ │ │ ├── __init__.py
315 | │ │ │ │ └── user.py
316 | │ │ │ ├── __init__.py
317 | │ │ │ └── utils.py
318 | │ │ ├── core
319 | │ │ │ ├── app_setup.py
320 | │ │ │ ├── database.py
321 | │ │ │ └── __init__.py
322 | │ │ ├── __init__.py
323 | │ │ ├── main.py
324 | │ │ └── models
325 | │ │ ├── __init__.py
326 | │ │ └── user.py
327 | │ └── uwsgi.ini
328 | └── Dockerfile
329 | ```
330 |
331 | * Make sure you follow [the official docs while importing your modules](https://docs.python.org/3/tutorial/modules.html#intra-package-references):
332 |
333 | * For example, if you are in `app/app/main.py` and want to import the module in `app/app/core/app_setup.py` you would write it like:
334 |
335 | ```python
336 | from .core import app_setup
337 | ```
338 |
339 | or
340 |
341 | ```python
342 | from app.core import app_setup
343 | ```
344 |
345 | * And if you are in `app/app/api/endpoints/user.py` and you want to import the `users` object from `app/app/core/database.py` you would write it like:
346 |
347 | ```python
348 | from ...core.database import users
349 | ```
350 |
351 | or
352 |
353 | ```python
354 | from app.core.database import users
355 | ```
356 |
357 | ## Advanced instructions
358 |
359 | You can customize several things using environment variables.
360 |
361 | ### Serve `index.html` directly
362 |
363 | **Notice**: this technique is deprecated, as it can create several issues with modern frontend frameworks. For the details and better alternatives, read the section above.
364 |
365 | Setting the environment variable `STATIC_INDEX` to be `1` you can configure Nginx to serve the file in the URL `/static/index.html` when requested for `/`.
366 |
367 | That would improve speed as it would not involve uWSGI nor Python. Nginx would serve the file directly. To learn more follow the section above "**QuickStart for SPAs**".
368 |
369 | For example, to enable it, you could add this to your `Dockerfile`:
370 |
371 | ```Dockerfile
372 | ENV STATIC_INDEX 1
373 | ```
374 |
375 | ### Custom uWSGI process number
376 |
377 | By default, the image starts with 2 uWSGI processes running. When the server is experiencing a high load, it creates up to 16 uWSGI processes to handle it on demand.
378 |
379 | If you need to configure these numbers you can use environment variables.
380 |
381 | The starting number of uWSGI processes is controlled by the variable `UWSGI_CHEAPER`, by default set to `2`.
382 |
383 | The maximum number of uWSGI processes is controlled by the variable `UWSGI_PROCESSES`, by default set to `16`.
384 |
385 | Have in mind that `UWSGI_CHEAPER` must be lower than `UWSGI_PROCESSES`.
386 |
387 | So, if, for example, you need to start with 4 processes and grow to a maximum of 64, your `Dockerfile` could look like:
388 |
389 | ```Dockerfile
390 | FROM tiangolo/uwsgi-nginx-flask:python3.12
391 |
392 | ENV UWSGI_CHEAPER 4
393 | ENV UWSGI_PROCESSES 64
394 |
395 | COPY ./app /app
396 | ```
397 |
398 | ### Max upload file size
399 |
400 | You can set a custom maximum upload file size using an environment variable `NGINX_MAX_UPLOAD`, by default it has a value of `0`, that allows unlimited upload file sizes. This differs from Nginx's default value of 1 MB. It's configured this way because that's the simplest experience an inexperienced developer in Nginx would expect.
401 |
402 | For example, to have a maximum upload file size of 1 MB (Nginx's default) add a line in your `Dockerfile` with:
403 |
404 | ```Dockerfile
405 | ENV NGINX_MAX_UPLOAD 1m
406 | ```
407 |
408 | ### Custom listen port
409 |
410 | By default, the container made from this image will listen on port 80.
411 |
412 | To change this behavior, set the `LISTEN_PORT` environment variable. You might also need to create the respective `EXPOSE` Docker instruction.
413 |
414 | You can do that in your `Dockerfile`, it would look something like:
415 |
416 | ```Dockerfile
417 | FROM tiangolo/uwsgi-nginx-flask:python3.12
418 |
419 | ENV LISTEN_PORT 8080
420 |
421 | EXPOSE 8080
422 |
423 | COPY ./app /app
424 | ```
425 |
426 | ### Custom `uwsgi.ini` configurations
427 |
428 | There is a default file in `/app/uwsgi.ini` with app specific configurations (on top of the global `uwsgi` configurations).
429 |
430 | It only contains:
431 |
432 | ```ini
433 | [uwsgi]
434 | module = main
435 | callable = app
436 | ```
437 |
438 | * `module = main` refers to the file `main.py`.
439 | * `callable = app` refers to the `Flask` "application", in the variable `app`.
440 |
441 | ---
442 |
443 | You can customize `uwsgi` by replacing that file with your own, including all your configurations.
444 |
445 | For example, to extend the default one above and enable threads, you could have a file:
446 |
447 | ```ini
448 | [uwsgi]
449 | module = main
450 | callable = app
451 | enable-threads = true
452 | ```
453 |
454 | ### Custom `uwsgi.ini` file location
455 |
456 | You can override where the image should look for the app `uwsgi.ini` file using the environment variable `UWSGI_INI`.
457 |
458 | With that you could change the default directory for your app from `/app` to something else, like `/application`.
459 |
460 | For example, to make the image use the file in `/application/uwsgi.ini`, you could add this to your `Dockerfile`:
461 |
462 | ```Dockerfile
463 | ENV UWSGI_INI /application/uwsgi.ini
464 |
465 | COPY ./application /application
466 | WORKDIR /application
467 | ```
468 |
469 | **Note**: the `WORKDIR` is important, otherwise uWSGI will try to run the app in `/app`.
470 |
471 | **Note**: you would also have to configure the `static` files path, read below.
472 |
473 | ### Custom `./static/` path
474 |
475 | You can make Nginx use a custom directory path with the files to serve directly (without having uWSGI involved) with the environment variable `STATIC_PATH`.
476 |
477 | For example, to make Nginx serve the static content using the files in `/app/custom_static/` you could add this to your `Dockerfile`:
478 |
479 | ```Dockerfile
480 | ENV STATIC_PATH /app/custom_static
481 | ```
482 |
483 | Then, when the browser asked for a file in, for example, http://example.com/static/index.html, Nginx would answer directly using a file in the path `/app/custom_static/index.html`.
484 |
485 | **Note**: you would also have to configure Flask to use that as its `static` directory.
486 |
487 | ---
488 |
489 | As another example, if you needed to put your application code in a different directory, you could configure Nginx to serve those static files from that different directory.
490 |
491 | If you needed to have your static files in `/application/static/` you could add this to your `Dockerfile`:
492 |
493 | ```Dockerfile
494 | ENV STATIC_PATH /application/static
495 | ```
496 |
497 | ### Custom `/static` URL
498 |
499 | You can also make Nginx serve the static files in a different URL, for that, you can use the environment variable `STATIC_URL`.
500 |
501 | For example, if you wanted to change the URL `/static` to `/content` you could add this to your `Dockerfile`:
502 |
503 | ```Dockerfile
504 | ENV STATIC_URL /content
505 | ```
506 |
507 | Then, when the browser asked for a file in, for example, http://example.com/content/index.html, Nginx would answer directly using a file in the path `/app/static/index.html`.
508 |
509 | ### Custom `/app/prestart.sh`
510 |
511 | If you need to run anything before starting the app, you can add a file `prestart.sh` to the directory `/app`. The image will automatically detect and run it before starting everything.
512 |
513 | For example, if you want to add Alembic SQL migrations (with SQLAlchemy), you could create a `./app/prestart.sh` file in your code directory (that will be copied by your `Dockerfile`) with:
514 |
515 | ```bash
516 | #! /usr/bin/env bash
517 |
518 | # Let the DB start
519 | sleep 10;
520 | # Run migrations
521 | alembic upgrade head
522 | ```
523 |
524 | and it would wait 10 seconds to give the database some time to start and then run that `alembic` command.
525 |
526 | If you need to run a Python script before starting the app, you could make the `/app/prestart.sh` file run your Python script, with something like:
527 |
528 | ```bash
529 | #! /usr/bin/env bash
530 |
531 | # Run custom Python script before starting
532 | python /app/my_custom_prestart_script.py
533 | ```
534 |
535 | **Note**: The image uses `source` to run the script, so for example, environment variables would persist. If you don't understand the previous sentence, you probably don't need it.
536 |
537 | ### Custom Nginx processes number
538 |
539 | By default, Nginx will start one "worker process".
540 |
541 | If you want to set a different number of Nginx worker processes you can use the environment variable `NGINX_WORKER_PROCESSES`.
542 |
543 | You can use a specific single number, e.g.:
544 |
545 | ```Dockerfile
546 | ENV NGINX_WORKER_PROCESSES 2
547 | ```
548 |
549 | or you can set it to the keyword `auto` and it will try to auto-detect the number of CPUs available and use that for the number of workers.
550 |
551 | For example, using `auto`, your Dockerfile could look like:
552 |
553 | ```Dockerfile
554 | FROM tiangolo/uwsgi-nginx-flask:python3.12
555 |
556 | ENV NGINX_WORKER_PROCESSES auto
557 |
558 | COPY ./app /app
559 | ```
560 |
561 | ### Custom Nginx maximum connections per worker
562 |
563 | By default, Nginx will start with a maximum limit of 1024 connections per worker.
564 |
565 | If you want to set a different number you can use the environment variable `NGINX_WORKER_CONNECTIONS`, e.g:
566 |
567 | ```Dockerfile
568 | ENV NGINX_WORKER_CONNECTIONS 2048
569 | ```
570 |
571 | It cannot exceed the current limit on the maximum number of open files. See how to configure it in the next section.
572 |
573 | ### Custom Nginx maximum open files
574 |
575 | The number connections per Nginx worker cannot exceed the limit on the maximum number of open files.
576 |
577 | You can change the limit of open files with the environment variable `NGINX_WORKER_OPEN_FILES`, e.g.:
578 |
579 | ```Dockerfile
580 | ENV NGINX_WORKER_OPEN_FILES 2048
581 | ```
582 |
583 | ### Customizing Nginx additional configurations
584 |
585 | If you need to configure Nginx further, you can add `*.conf` files to `/etc/nginx/conf.d/` in your `Dockerfile`.
586 |
587 | Just have in mind that the default configurations are created during startup in a file at `/etc/nginx/conf.d/nginx.conf` and `/etc/nginx/conf.d/upload.conf`. So you shouldn't overwrite them. You should name your `*.conf` file with something different than `nginx.conf` or `upload.conf`, for example: `custom.conf`.
588 |
589 | **Note**: if you are customizing Nginx, maybe copying configurations from a blog or a StackOverflow answer, have in mind that you probably need to use the [configurations specific to uWSGI](http://nginx.org/en/docs/http/ngx_http_uwsgi_module.html), instead of those for other modules, like for example, `ngx_http_fastcgi_module`.
590 |
591 | ### Overriding Nginx configuration completely
592 |
593 | If you need to configure Nginx even further, completely overriding the defaults, you can add a custom Nginx configuration to `/app/nginx.conf`.
594 |
595 | It will be copied to `/etc/nginx/nginx.conf` and used instead of the generated one.
596 |
597 | Have in mind that, in that case, this image won't generate any of the Nginx configurations, it will only copy and use your configuration file.
598 |
599 | That means that all the environment variables described above that are specific to Nginx won't be used.
600 |
601 | It also means that it won't use additional configurations from files in `/etc/nginx/conf.d/*.conf`, unless you explicitly have a section in your custom file `/app/nginx.conf` with:
602 |
603 | ```conf
604 | include /etc/nginx/conf.d/*.conf;
605 | ```
606 |
607 | If you want to add a custom `/app/nginx.conf` file but don't know where to start from, you can use [the `nginx.conf` used for the tests](https://github.com/tiangolo/uwsgi-nginx-flask-docker/blob/master/tests/test_02_app/custom_nginx_app/app/nginx.conf) and customize it or modify it further.
608 |
609 | ## Technical details
610 |
611 | The combination of uWSGI with Nginx is a [common way to deploy Python Flask web applications](http://flask.pocoo.org/docs/1.0/deploying/uwsgi/).
612 |
613 | Roughly:
614 |
615 | * **Nginx** is a web server, it takes care of the HTTP connections and also can serve static files directly and more efficiently.
616 |
617 | * **uWSGI** is an application server, that's what runs your Python code and it talks with Nginx.
618 |
619 | * **Your Python code** has the actual **Flask** web application, and is run by uWSGI.
620 |
621 | The image [**tiangolo/uwsgi-nginx**](https://hub.docker.com/r/tiangolo/uwsgi-nginx/) takes advantage of already existing slim and optimized Docker images (based on Debian as [recommended by Docker](https://docs.docker.com/engine/userguide/eng-image/dockerfile_best-practices/)) and implements several of Docker's best practices.
622 |
623 | It uses the official Python Docker image, installs uWSGI and on top of that (with the least amount of modifications) adds the official Nginx image.
624 |
625 | And it controls all these processes with Supervisord.
626 |
627 | The image (and tags) created by this repo is based on the image [**tiangolo/uwsgi-nginx**](https://hub.docker.com/r/tiangolo/uwsgi-nginx/). This image adds Flask and sensible defaults on top of it.
628 |
629 | If you follow the instructions and keep the root directory `/app` in your container, with a file named `main.py` and a Flask object named `app` in it, it should "just work".
630 |
631 | There's already a `uwsgi.ini` file in the `/app` directory with the uWSGI configurations for it to "just work". And all the other required parameters are in another `uwsgi.ini` file in the image, inside `/etc/uwsgi/`.
632 |
633 | If you need to change the main file name or the main Flask object, you would have to provide your own `uwsgi.ini` file. You may use the one in this repo as a template to start with (and you only would have to change the 2 corresponding lines).
634 |
635 | You can have a `/app/static` directory and those files will be efficiently served by Nginx directly (without going through your Flask code or even uWSGI), it's already configured for you. But you can configure it further using environment variables (read above).
636 |
637 | Supervisord takes care of running uWSGI with the `uwsgi.ini` file in `/app` file (including also the file in `/etc/uwsgi/uwsgi.ini`) and starting Nginx.
638 |
639 | ---
640 |
641 | There's the rule of thumb that you should have "one process per container".
642 |
643 | That helps, for example, isolating an app and its database in different containers.
644 |
645 | But if you want to have a "micro-services" approach you may want to [have more than one process in one container](https://valdhaus.co/writings/docker-misconceptions/) if they are all related to the same "service", and you may want to include your Flask code, uWSGI and Nginx in the same container (and maybe run another container with your database).
646 |
647 | That's the approach taken in this image.
648 |
649 | ---
650 |
651 | This image (and tags) have some default files, so if you run it by itself (not as the base image of your own project) you will see a default "Hello World" web app.
652 |
653 | When you build a `Dockerfile` with a `COPY ./app /app` you replace those default files with your app code.
654 |
655 | The main default file is only in `/app/main.py`. And in the case of the tags with `-index`, also in `/app/static/index.html`.
656 |
657 | But those files render a "(default)" text in the served web page, so that you can check if you are seeing the default code or your own code overriding the default.
658 |
659 | Your app code should be in the container's `/app` directory, it should have a `main.py` file and that `main.py` file should have a Flask object `app`.
660 |
661 | If you follow the instructions above or use one of the downloadable example templates, you should be OK.
662 |
663 | There is also a `/app/uwsgi.ini` file inside the images with the default parameters for uWSGI.
664 |
665 | The downloadable examples include a copy of the same `uwsgi.ini` file for debugging purposes. To learn more, read the "**Advanced development instructions**" below.
666 |
667 | ## Advanced development instructions
668 |
669 | While developing, you might want to make your code directory a volume in your Docker container.
670 |
671 | With that you would have your files (temporarily) updated every time you modify them, without needing to build your container again.
672 |
673 | To do this, you can use the command `pwd` (print working directory) inside your `docker run` and the flag `-v` for volumes.
674 |
675 | With that you could map your `./app` directory to your container's `/app` directory.
676 |
677 | But first, as you will be completely replacing the directory `/app` in your container (and all of its contents) you will need to have a `uwsgi.ini` file in your `./app` directory with:
678 |
679 | ```ini
680 | [uwsgi]
681 | module = main
682 | callable = app
683 | ```
684 |
685 | and then you can do the Docker volume mapping.
686 |
687 | **Note**: A `uwsgi.ini` file is included in the downloadable examples.
688 |
689 | * To try it, go to your project directory (the one with your `Dockerfile` and your `./app` directory)
690 | * Make sure you have a `uwsgi.ini` file in your `./app` directory
691 | * Build your Docker image:
692 |
693 | ```bash
694 | docker build -t myimage .
695 | ```
696 |
697 | * Run a container based on your image, mapping your code directory (`./app`) to your container's `/app` directory:
698 |
699 | ```bash
700 | docker run -d --name mycontainer -p 80:80 -v $(pwd)/app:/app myimage
701 | ```
702 |
703 | If you go to your Docker container URL you should see your app, and you should be able to modify files in `./app/static/` and see those changes reflected in your browser just by reloading.
704 |
705 | ...but, as uWSGI loads your whole Python Flask web application once it starts, you won't be able to edit your Python Flask code and see the changes reflected.
706 |
707 | To be able to (temporarily) debug your Python Flask code live, you can run your container overriding the default command (that starts Supervisord which in turn starts uWSGI and Nginx) and run your application directly with `python`, in debug mode, using the `flask` command with its environment variables.
708 |
709 | So, with all the modifications above and making your app run directly with `flask`, the final Docker command would be:
710 |
711 | ```bash
712 | docker run -d --name mycontainer -p 80:80 -v $(pwd)/app:/app -e FLASK_APP=main.py -e FLASK_DEBUG=1 myimage flask run --host=0.0.0.0 --port=80
713 | ```
714 |
715 | Or in the case of a package project, you would set `FLASK_APP=main/main.py`:
716 |
717 | ```bash
718 | docker run -d --name mycontainer -p 80:80 -v $(pwd)/app:/app -e FLASK_APP=main/main.py -e FLASK_DEBUG=1 myimage flask run --host=0.0.0.0 --port=80
719 | ```
720 |
721 | Now you can edit your Flask code in your local machine and once you refresh your browser, you will see the changes live.
722 |
723 | Remember that you should use this only for debugging and development, for deployment in production you shouldn't mount volumes and you should let Supervisord start and let it start uWSGI and Nginx (which is what happens by default).
724 |
725 | An alternative for these last steps to work when you don't have a package, but just a flat structure with single files (modules), your Python Flask code could have that section with:
726 |
727 | ```python
728 | if __name__ == "__main__":
729 | # Only for debugging while developing
730 | app.run(host='0.0.0.0', debug=True, port=80)
731 | ```
732 |
733 | ...and you could run it with `python main.py`. But that will only work when you are not using a package structure and don't plan to do it later. In that specific case, if you didn't add the code block above, your app would only listen to `localhost` (inside the container), in another port (5000) and not in debug mode.
734 |
735 | ---
736 |
737 | Also, if you want to do the same live debugging using the environment variable `STATIC_INDEX=1` (to serve `/app/static/index.html` directly when requested for `/`) your Nginx won't serve it directly as it won't be running (only your Python Flask app in debug mode will be running).
738 |
739 | ```python
740 | from flask import Flask, send_file
741 | ```
742 |
743 | and
744 |
745 | ```python
746 | @app.route('/')
747 | def route_root():
748 | index_path = os.path.join(app.static_folder, 'index.html')
749 | return send_file(index_path)
750 | ```
751 |
752 | ...that makes sure your app also serves the `/app/static/index.html` file when requested for `/`. Or if you are using a package structure, the `/app/main/static/index.html` file.
753 |
754 | And if you are using a SPA framework, to allow it to handle the URLs in the browser, your Python Flask code should have the section with:
755 |
756 | ```python
757 | # Everything not declared before (not a Flask route / API endpoint)...
758 | @app.route('/')
759 | def route_frontend(path):
760 | # ...could be a static file needed by the front end that
761 | # doesn't use the `static` path (like in `