Docker Python App
A python app needed to be Dockerized, and then it needs to be deployed on App Server 3. We have already copied a requirements.txt file (having the app dependencies) under /python_app/src/ directory on App Server 3. Further complete this task as per details mentioned below:
-
Create a Dockerfile under /python_app directory:
- Use any python image as the base image.
- Install the dependencies using requirements.txt file.
- Expose the port 6300.
- Run the server.py script using CMD.
-
Build an image named nautilus/python-app using this Dockerfile.
-
Once image is built, create a container named pythonapp_nautilus:
- Map port 6300 of the container to the host port 8096.
-
Once deployed, you can test the app using curl command on App Server 3.
Steps
-
Login into App server and move into directory
-
Create Docker file and copy paste the contents:
FROM python:3.9.23-slim
WORKDIR /app
COPY ./src/* /app/
RUN pip install -r requirements.txt
EXPOSE 6300
CMD ["python", "server.py"]
-
Build Docker Image
docker build -t nautilus/python-app .
-
Run the container
docker run -d --name pythonapp_nautilus -p 8096:6300 nautilus/python-app
-
Verify
docker ps
curl http://localhost:8096
Good to Know?
Python Application Containerization
- Dependency Management: requirements.txt defines Python packages
- Virtual Environment: Container provides isolated Python environment
- Reproducibility: Same dependencies across all environments
- Portability: Run anywhere Docker is available
Python Docker Images
- Official Images: python:3.9, python:3.9-slim, python:3.9-alpine
- Size Optimization: Slim images exclude unnecessary packages
- Alpine: Minimal Linux distribution for smallest images
- Version Pinning: Use specific versions for consistency
Dockerfile Best Practices
- WORKDIR: Set working directory for organization
- COPY Order: Copy requirements.txt first for better caching
- Layer Optimization: Combine RUN commands when possible
- EXPOSE: Document which ports application uses
Application Deployment
- Port Mapping: Map container port to host port
- Health Checks: Verify application is responding
- Logging: Configure application logging
- Environment Variables: Use for configuration