Sign inSign up

khulnasoft/uwsgi-nginx-flask

By khulnasoft

•Updated about 2 years ago

Efficient Flask Hosting: uWSGI and Nginx Docker Image for Python Web Apps

Image
Developer tools
Web servers
0

10K+

khulnasoft/uwsgi-nginx-flask repository overview

Test Deploy

⁠Deprecated tags

🚨 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:

  • python3.8-alpine
  • python3.6
  • python2.7

The last date tags for these versions are:

  • python3.8-alpine-2024-03-11
  • python3.6-2022-11-25
  • python2.7-2022-11-25

Note: There are tags for each build date⁠. If you need to "pin" the Docker image version you use, you can select one of those tags. E.g. khulnasoft/uwsgi-nginx-flask:python3.7-2019-10-14.

⁠uwsgi-nginx-flask

Docker image with uWSGI and Nginx for Flask web applications in Python running in a single container.

⁠Description

This Docker⁠ image allows you to create Flask⁠ web applications in Python⁠ that run with uWSGI⁠ and Nginx⁠ in a single container.

The combination of uWSGI with Nginx is a common way to deploy Python Flask web applications⁠. It is widely used in the industry and would give you decent performance. (*)

There is also an Alpine version. If you want it, check the tags from above.

⁠* Note on performance and features

If you are starting a new project, you might benefit from a newer and faster framework based on ASGI instead of WSGI (Flask and Django are WSGI-based).

You could use an ASGI framework like:

ReadyAPI, or Starlette, would give you about 800% (8x) the performance achievable with Flask using this image (khulnasoft/uwsgi-nginx-flask). You can see the third-party benchmarks here⁠.

Also, if you want to use new technologies like WebSockets it would be easier (and possible) with a newer framework based on ASGI, like ReadyAPI or Starlette. As the standard ASGI was designed to be able to handle asynchronous code like the one needed for WebSockets.

⁠If you need Flask

If you need to use Flask (instead of something based on ASGI) and you need to have the best performance possible, you can use the alternative image: khulnasoft/meinheld-gunicorn-flask⁠.

khulnasoft/meinheld-gunicorn-flask will give you about 400% (4x) the performance of this image (khulnasoft/uwsgi-nginx-flask).

It is very similar to khulnasoft/uwsgi-nginx-flask, so you can still use many of the ideas described here.


GitHub repo: https://github.com/khulnasoft/uwsgi-nginx-flask-docker⁠

Docker Hub image: https://hub.docker.com/r/khulnasoft/uwsgi-nginx-flask/⁠

⁠🚨 WARNING: You Probably Don't Need this Docker Image

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.


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.

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.

For example, using Gunicorn⁠ you could have a file app/gunicorn_conf.py with:

# Gunicorn config variables
loglevel = "info"
errorlog = "-"  # stderr
accesslog = "-"  # stdout
worker_tmp_dir = "/dev/shm"
graceful_timeout = 120
timeout = 120
keepalive = 5
threads = 3

And then you could have a Dockerfile with:

FROM python:3.9

WORKDIR /code

COPY ./requirements.txt /code/requirements.txt

RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt

COPY ./app /code/app

CMD ["gunicorn", "--conf", "app/gunicorn_conf.py", "--bind", "0.0.0.0:80", "app.main:app"]

You can read more about these ideas in the ReadyAPI documentation about: ReadyAPI in Containers - Docker⁠ as the same ideas would apply to other web applications in containers.

⁠When to Use this Docker Image

⁠A Simple App

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.

⁠Docker Compose

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.

Then you could want to have a single container with a process manager starting several worker processes inside, as this Docker image does.

⁠Prometheus and Other Reasons

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.

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.

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.

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.


Read more about it all in the ReadyAPI documentation about: ReadyAPI in Containers - Docker⁠, as the same concepts apply to other web applications in containers.

⁠Examples (simple project templates)

  • python3.8 tag: general Flask web application:

example-flask-python3.8.zip⁠

  • python3.8 tag: general Flask web application, structured as a package, for bigger Flask projects, with different submodules. Use it only as an example of how to import your modules and how to structure your own project:

example-flask-package-python3.8.zip⁠

  • python3.8 tag: static/index.html served directly in /, e.g. for Vue⁠, React⁠, Angular⁠, or any other Single-Page Application that uses a static index.html, not modified by Python:

example-flask-python3.8-index.zip⁠

⁠General Instructions

You don't have to clone this repo.

You can use this image as a base image for other images.

Assuming you have a file requirements.txt, you could have a Dockerfile like this:

FROM khulnasoft/uwsgi-nginx-flask:python3.11

COPY ./requirements.txt /app/requirements.txt

RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt

COPY ./app /app

There are several image tags available but for new projects you should use the latest version available.

There are several template projects that you can download (as a .zip file) to bootstrap your project in the section "Examples (project templates)" above.

This Docker image is based on khulnasoft/uwsgi-nginx⁠. That Docker image has uWSGI and Nginx installed in the same container and was made to be the base of this image.

⁠Quick Start

Note: You can download the example-flask-python3.8.zip project example and use it as the template for your project from the section Examples above.


Or you may follow the instructions to build your project from scratch:

  • Go to your project directory
  • Create a Dockerfile with:
FROM khulnasoft/uwsgi-nginx-flask:python3.11

COPY ./app /app
  • Create an app directory and enter in it
  • Create a main.py file (it should be named like that and should be in your app directory) with:
from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World from Flask"

if __name__ == "__main__":
    # Only for debugging while developing
    app.run(host='0.0.0.0', debug=True, port=80)

the main application object should be named app (in the code) as in this example.

Note: The section with the main() function is for debugging purposes. To learn more, read the Advanced instructions below.

  • You should now have a directory structure like:
.
ā”œā”€ā”€ app
│   └── main.py
└── Dockerfile
  • Go to the project directory (in where your Dockerfile is, containing your app directory)
  • Build your Flask image:
docker build -t myimage .
  • Run a container based on your image:
docker run -d --name mycontainer -p 80:80 myimage

...and you have an optimized Flask server in a Docker container.

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⁠

⁠Project Generators

There are several project generators that you can use to start your project, with everything already configured.

⁠Server set up

All these project generators include automatic and free HTTPS certificates generation provided by:

...using the ideas from DockerSwarm.rocks⁠.

It would take about 20 minutes to read that guide and have a Docker cluster (of one or more servers) up and running ready for your projects.

You can have several projects in the same cluster, all with automatic HTTPS, even if they have different domains or sub-domains.

⁠Generate a project

Then you can use one of the following project generators.

It would take about 5 extra minutes to generate one of these projects.

⁠Deploy

And it would take about 3 more minutes to deploy them in your cluster.


In total, about 28 minutes to start from scratch and get an HTTPS Docker cluster with your full application(s) ready.


These are the project generators:

⁠flask-frontend-docker

Project link: https://github.com/khulnasoft/flask-frontend-docker⁠

Minimal project generator with a Flask backend, a modern frontend (Vue, React or Angular) using Docker multi-stage building and Nginx, a Traefik load balancer with HTTPS, Docker Compose (and Docker Swarm mode) etc.

⁠full-stack

Project Link: https://github.com/khulnasoft/full-stack⁠

Full stack project generator with Flask backend, PostgreSQL DB, PGAdmin, SQLAlchemy, Alembic migrations, Celery asynchronous jobs, API testing, CI integration, Docker Compose (and Docker Swarm mode), Swagger, automatic HTTPS, Vue.js, etc.

⁠full-stack-flask-couchbase

Project Link: https://github.com/khulnasoft/full-stack-flask-couchbase⁠

Full stack project generator with Flask backend, Couchbase, Couchbase Sync Gateway, Celery asynchronous jobs, API testing, CI integration, Docker Compose (and Docker Swarm mode), Swagger, automatic HTTPS, Vue.js, etc.

Similar to the one above (full-stack), but with Couchbase instead of PostgreSQL, and some more features.

⁠full-stack-flask-couchdb

Project Link: https://github.com/khulnasoft/full-stack-flask-couchdb⁠

Full stack project generator with Flask backend, CouchDB, Celery asynchronous jobs, API testing, CI integration, Docker Compose (and Docker Swarm mode), Swagger, automatic HTTPS, Vue.js, etc.

Similar to full-stack-flask-couchbase, but with CouchDB instead of Couchbase (or PostgreSQL).

⁠Quick Start for SPAs *

⁠Modern Single Page Applications

If you are building modern frontend applications (e.g. Vue⁠, React⁠, Angular⁠) you would most probably be compiling a modern version of JavaScript (ES2015, TypeScript, etc) to a less modern, more compatible version.

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.

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).

That also means that you would have to, somehow, always remember to compile the frontend code right before building the Docker image.

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⁠).

Adding your compiled code to Git is a very bad idea for several reasons, some of those are:

  • You don't have a single, ultimate source of truth (the source code).
  • The compiled code might be stale, even when your source code is new, which might make you spend a lot of time debugging.
  • 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.
    • This might also ruin automatic branch merging in pull requests from other team members.

For these reasons, it is not recommended that you serve your frontend code from the same backend (Flask) Docker container.

⁠Better alternative

There's a much better alternative to serving your frontend code from the same backend (Flask) Docker container.

You can have another Docker container with all the frontend tools installed (Node.js, etc) that:

  • Takes your source frontend code.
  • Compiles it and generates the final "distributable" frontend.
  • Uses Docker "multi-stage builds" to copy that compiled code into a pure Nginx Docker image.
  • 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.

To learn the specifics of this process for the frontend building in Docker you can read:

After having one backend (Flask) container and one frontend container, you need to serve both of them.

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 /.

You can then use Traefik⁠ to handle that.

And it can also automatically generate HTTPS certificates for your application using Let's Encrypt. All for free, in a very easy setup.

If you want to use this alternative, check the project generators above⁠, they all use this idea.

In this scenario, you would have 3 Docker containers:

  • Backend (Flask)
  • Frontend (Vue.js, Angular, React or any other)
  • Traefik (load balancer, HTTPS)
⁠Deprecated Single Page Applications guide

If you want to check the previous (deprecated) documentation on adding a frontend to the same container, you can read the deprecated guide for single page apps⁠.

⁠Quick Start for bigger projects structured as a Python package

Note: You can download the example-flask-package-python3.8.zip project example and use it as an example or template for your project from the section Examples above.


You should be able to follow the same instructions as in the "QuickStart" section above, with some minor modifications:

  • Instead of putting your code in the app/ directory, put it in a directory app/app/.
  • Add an empty file __init__.py inside of that app/app/ directory.
  • Add a file uwsgi.ini inside your app/ directory (that is copied to /app/uwsgi.ini inside the container).
  • In your uwsgi.ini file, add:
[uwsgi]
module = app.main
callable = app

The explanation of the uwsgi.ini is as follows:

  • 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).
  • The Flask web application is the app object (app = Flask(__name__)).

Your file structure would look like:

.
ā”œā”€ā”€ app
│   ā”œā”€ā”€ app
│   │   ā”œā”€ā”€ __init__.py
│   │   ā”œā”€ā”€ main.py
│   └── uwsgi.ini
└── Dockerfile

...instead of:

.
ā”œā”€ā”€ app
│   ā”œā”€ā”€ main.py
└── Dockerfile

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:

ENV STATIC_PATH /app/app/static

...after that, everything should work as expected. All the other instructions would apply normally.

⁠Working with submodules
  • After adding all your modules you could end up with a file structure similar to (taken from the example project):
.
ā”œā”€ā”€ app
│   ā”œā”€ā”€ app
│   │   ā”œā”€ā”€ api
│   │   │   ā”œā”€ā”€ api.py
│   │   │   ā”œā”€ā”€ endpoints
│   │   │   │   ā”œā”€ā”€ __init__.py
│   │   │   │   └── user.py
│   │   │   ā”œā”€ā”€ __init__.py
│   │   │   └── utils.py
│   │   ā”œā”€ā”€ core
│   │   │   ā”œā”€ā”€ app_setup.py
│   │   │   ā”œā”€ā”€ database.py
│   │   │   └── __init__.py
│   │   ā”œā”€ā”€ __init__.py
│   │   ā”œā”€ā”€ main.py
│   │   └── models
│   │       ā”œā”€ā”€ __init__.py
│   │       └── user.py
│   └── uwsgi.ini
└── Dockerfile
from .core import app_setup

or

from app.core import app_setup
  • 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:
from ...core.database import users

or

from app.core.database import users

⁠Advanced instructions

You can customize several things using environment variables.

⁠Serve index.html directly

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.

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 /.

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".

For example, to enable it, you could add this to your Dockerfile:

ENV STATIC_INDEX 1
⁠Custom uWSGI process number

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.

If you need to configure these numbers you can use environment variables.

The starting number of uWSGI processes is controlled by the variable UWSGI_CHEAPER, by default set to 2.

The maximum number of uWSGI processes is controlled by the variable UWSGI_PROCESSES, by default set to 16.

Have in mind that UWSGI_CHEAPER must be lower than UWSGI_PROCESSES.

So, if, for example, you need to start with 4 processes and grow to a maximum of 64, your Dockerfile could look like:

FROM khulnasoft/uwsgi-nginx-flask:python3.11

ENV UWSGI_CHEAPER 4
ENV UWSGI_PROCESSES 64

COPY ./app /app
⁠Max upload file size

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.

For example, to have a maximum upload file size of 1 MB (Nginx's default) add a line in your Dockerfile with:

ENV NGINX_MAX_UPLOAD 1m
⁠Custom listen port

By default, the container made from this image will listen on port 80.

To change this behavior, set the LISTEN_PORT environment variable. You might also need to create the respective EXPOSE Docker instruction.

You can do that in your Dockerfile, it would look something like:

FROM khulnasoft/uwsgi-nginx-flask:python3.11

ENV LISTEN_PORT 8080

EXPOSE 8080

COPY ./app /app
⁠Custom uwsgi.ini configurations

There is a default file in /app/uwsgi.ini with app specific configurations (on top of the global uwsgi configurations).

It only contains:

[uwsgi]
module = main
callable = app
  • module = main refers to the file main.py.
  • callable = app refers to the Flask "application", in the variable app.

You can customize uwsgi by replacing that file with your own, including all your configurations.

For example, to extend the default one above and enable threads, you could have a file:

[uwsgi]
module = main
callable = app
e

Tag summary

Content type

Image

Digest

sha256:502bf0690…

Size

342.9 MB

Last updated

about 2 years ago

docker pull khulnasoft/uwsgi-nginx-flask