Creating and Managing Docker Images and Containers
Docker Images
Definition:
A Docker image is a read-only template that contains an application, its dependencies, and instructions to run it in a container.
Creating Docker Images:
- Using a Dockerfile:
- A
Dockerfiledefines how to build an image. - Example:
# Use official Python base image FROM python:3.11-slim # Set working directory WORKDIR /app # Copy application code COPY . /app # Install dependencies RUN pip install --no-cache-dir -r requirements.txt # Run the app CMD ["python", "app.py"]
- A
- Build the image:
docker build -t my-python-app:1.0 . - List available images:
docker images - Push image to a registry (optional):
docker tag my-python-app:1.0 username/my-python-app:1.0 docker push username/my-python-app:1.0
Docker Containers
Definition:
A container is a running instance of a Docker image. It is isolated but shares the host OS kernel.
Managing Containers:
- Run a container:
docker run -d --name my-app -p 5000:5000 my-python-app:1.0-d: Run in detached mode--name: Assign a custom name-p: Map host port to container port
- List running containers:
docker ps - List all containers (including stopped):
docker ps -a - Stop a container:
docker stop my-app - Remove a container:
docker rm my-app - Access a container shell:
docker exec -it my-app /bin/bash
Managing Volumes and Networks
- Volumes:
- Persist data beyond the container lifecycle.
- Create a volume:
docker volume create my-data - Mount a volume to a container:
docker run -v my-data:/app/data my-python-app:1.0
- Networks:
- Connect multiple containers for communication.
- Example:
docker network create my-network docker run --network my-network --name app1 my-python-app docker run --network my-network --name app2 my-python-app
4. Best Practices
- Use lightweight base images to reduce image size.
- Keep Dockerfiles small and modular, with minimal layers.
- Version your images (tags) for better rollback and reproducibility.
- Remove unused images and containers regularly (
docker system prune). - Use multi-stage builds for production to keep images lean.
5. Typical Workflow
- Write a
Dockerfile. - Build the image using
docker build. - Test by running a container (
docker run). - Push image to a registry if needed.
- Deploy containers in development, staging, or production.
- Monitor and manage containers and volumes over time.