Docker provides a great way to containerize Python web applications like those built with aiohttp. However, there are some specific considerations when running asyncio apps in Docker that are worth covering.
Choosing the Right Base Image
Since aiohttp relies on asyncio, you'll want to use a Python base image that has support for asyncio. The smaller Python base images like
FROM python:3.7-slim
Installing Dependencies
Use pip to install aiohttp and other app dependencies. Make sure to also install
RUN pip install aiohttp uvloop
Configuring Number of Workers
By default, the number of asyncio worker processes will be based on the number of CPU cores available. This can lead to too many workers when running in Docker with limited cores. Set the environment variable
ENV AIOHTTP_WORKERS=2
Avoiding Port Collisions
If you scale up the number of containers, you can run into issues with port collisions on the host machine. Map to a dynamic port instead with 0:
EXPOSE 0
And then get the assigned port at runtime.
Graceful Shutdowns
Handle SIGTERM signals to trigger a graceful shutdown and finalize requests properly.
In summary, running aiohttp web apps in Docker introduces some special considerations but is very achievable with the right base image, dependencies, and config. Focus on limiting workers, dynamic ports, and graceful shutdowns.