16 Docker#
Goal#
Learn how to use Docker to containerize your Python applications and ensure consistent environments across different machines. Docker allows you to package your code and all its dependencies into a container that works the same way everywhere.
Prerequisites#
Steps#
1. Introduction#
Docker is a platform that uses containerization to allow developers to package applications and their dependencies into a standardized unit called a container. Containers are lightweight, portable, and can run on any system that has Docker installed.
2. Setup#
### 2.1 Installing Docker
Download Docker Desktop for your operating system from their website
Install following the instructions
Verify installtion running
docker --version
2.2 Basic Docker Concepts#
Images: Read-only templates used to create containers. Images are built from Dockerfiles
Containers: Running instances of images. Containers are isolated and portable.
Dockerfile: A text file that defines the steps to create a Docker image.
Docker Hub: A repository where Docker images are stored and shared.
3. Execution#
3.1 Basic Docker Commands#
Check Docker installation:
docker infoSearch for an image:
docker search <image-name>Pull an image:
docker pull <image-name>Run a container:
docker run -it <image-name>List running containers:
docker psList all containers:
docker ps -aStop a container:
docker stop <container-id>Remove a container:
docker rm <container-id>List docker images:
docker imagesRemove an image:
docker rmi <image-name>
3.2 Creating a Dockerfile#
Create a file running touch <dockerfilename>and write it like:
# Use the official Python image from the Docker Hub
FROM python:3.9
# Set the working directory in the container
WORKDIR /<your-directory>
# Copy the requirements file into the container
COPY requirements.txt .
# Install the dependencies
RUN pip install --no-cache-dir -r requirements.txt
# Copy the rest of your application code
COPY . .
# Command to run your application
CMD ["python", "your_script.py"]
3.3 Building and Running the Image#
docker build t <image-name> .
docker run -it <image-name> <command-to-run>
docker run -it dockerfile python new_script.py
Troubleshooting#
Visit the official Docker documentation.
Next Steps#
Docker is particularly useful when collaborating on projects with team members using different operating systems, or when you want to ensure your code runs consistently in production. Next, learn about tracking environmental impact of your code: 18 CodeCarbon.