Singleton
What’s Singleton?
Single process per container.
Imagine a web using Nginx + PHP to host.
How would you do the containerized?
Two process in a single container?
Or split it into two containers?
Let’s check the following table:
Comparison Aspect | Single Process per Container | Two Processes in a Single Container |
---|---|---|
Isolation | High. Each process runs in its own container, without interference. | Low. Two processes run in the same container, potentially affecting each other. |
Scalability | High. Each process can be scaled independently. | Low. Both processes have to be scaled together. |
Management Complexity | Medium. Multiple containers need to be managed. | Low. Only one container needs to be managed. |
Resource Usage | Potentially higher. Each container requires its own system resources. | Potentially lower. Both processes share the resources of a single container. |
Fault Isolation | High. A failure in one process does not affect other processes. | Low. A failure in one process may affect the other process in the same container. |
This is what the “Singleton” practice, using this practice will provide better isolation and fault tolerance, as a failure in one process does not affect other processes. It also offers higher scalability, as each process can be scaled independently.
While the Singleton approach might require more system resources and involve more management complexity, these trade-offs can often be justified by the benefits of improved scalability and fault isolation.
Example
Python with FastAPI
1 2 3 4 5 6 7
from fastapi import FastAPI app = FastAPI() @app.get("/") def read_root(): return {"Hello": "World"}
Dockerfile
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# Use an official Python runtime as a parent image FROM python:3.9-slim-buster # Set the working directory in the container to /app WORKDIR /app # Add the current directory contents into the container at /app ADD . /app # Install any needed packages specified in requirements.txt RUN pip install --no-cache-dir -r requirements.txt # Make port 80 available to the world outside this container EXPOSE 80 # Run app.py when the container launches CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "80"]
Please take a look of line #17 in Dockerfile, that’s the point I mean. The only process in this container is uvicorn, which is the web server process for Python.