Building Docker Development Environments
Creating a Dockerfile
A Dockerfile is a text file that contains all the commands needed to build a Docker image. Here's an example Dockerfile for a simple Python web application:
FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["python", "app.py"]
This Dockerfile:
- Starts from the
python:3.9-slim
base image.
- Sets the working directory to
/app
.
- Copies the
requirements.txt
file to the working directory.
- Installs the Python dependencies listed in
requirements.txt
.
- Copies the application code to the working directory.
- Specifies the command to run the application (
python app.py
).
Building a Docker Image
To build a Docker image from the Dockerfile, run the following command in the same directory as the Dockerfile:
docker build -t my-python-app .
This will build a Docker image with the tag my-python-app
.
Running a Docker Container
To run a Docker container from the my-python-app
image, use the following command:
docker run -p 8080:8080 my-python-app
This will start a new container and map port 8080 on the host to port 8080 in the container.
Developing with Docker Compose
Docker Compose is a tool for defining and running multi-container Docker applications. Here's an example docker-compose.yml
file for a simple web application with a database:
version: "3"
services:
web:
build: .
ports:
- 8080:8080
depends_on:
- db
db:
image: postgres:13
environment:
POSTGRES_DB: myapp
POSTGRES_USER: myapp
POSTGRES_PASSWORD: secret
volumes:
- db-data:/var/lib/postgresql/data
volumes:
db-data:
This docker-compose.yml
file defines two services: web
and db
. The web
service builds a Docker image from the current directory and maps port 8080 on the host to port 8080 in the container. The db
service uses the official PostgreSQL image and sets up a database for the application.
To start the application, run:
docker-compose up -d
This will start the web
and db
containers in the background.