Docker is an open platform for developing, shipping, and running applications. Docker enables you to separate your applications from your infrastructure so that you can deliver software faster. With Docker, you can:
- Package an application in a container with its dependencies.
- Run containers on any machine, whether it's a local laptop, a physical server, or a cloud virtual machine.
- Manage containers using Docker commands and tools.
This approach provides a consistent environment across development, testing, and production, significantly reducing "it works on my machine" issues.
Core Concepts: Images and Containers
At the heart of Docker are two main entities:
Docker Images:
A Docker image is a lightweight, standalone, executable package that includes everything needed to run a piece of software, including the code, runtime, system tools, system libraries, and settings.
# Example Dockerfile snippet
FROM ubuntu:latest
RUN apt-get update && apt-get install -y python3
COPY . /app
WORKDIR /app
CMD ["python3", "app.py"]
Docker Containers:
A Docker container is a runnable instance of a Docker image. You can create, start, stop, move, or delete a container using the Docker API or CLI. A container is the running process.
When you run an image, you create a container. The container is an isolated environment where your application runs.
Getting Started with Docker
To begin, you'll need to install Docker Desktop on your machine. Once installed, you can start interacting with Docker using the command-line interface (CLI).
Here are some common commands:
docker build -t my-app .
: Builds an image from a Dockerfile.docker run -p 8080:80 my-app
: Runs a container from an image, mapping host port 8080 to container port 80.docker ps
: Lists running containers.docker images
: Lists available Docker images.docker stop <container_id>
: Stops a running container.
Best Practices for Docker Development
- Minimize image size: Use smaller base images and multistage builds.
- Keep images secure: Regularly update base images and dependencies.
- Leverage caching: Order Dockerfile instructions to maximize layer caching.
- Use `.dockerignore`: Prevent unnecessary files from being copied into the image.
- Single process per container: Design containers to run a single primary process.