Docker Container Basics
What is a Docker Container?
A Docker container is a lightweight, standalone, executable package that includes everything needed to run an application: code, runtime, system tools, libraries, and settings. Containers provide a consistent and reproducible environment across different computing platforms.
Key Characteristics of Docker Containers
Characteristic |
Description |
Isolation |
Containers run in isolated user spaces |
Portability |
Can run consistently across different environments |
Efficiency |
Lightweight and share host system's kernel |
Scalability |
Easy to scale up or down quickly |
Container Lifecycle Management
stateDiagram-v2
[*] --> Created
Created --> Running
Running --> Paused
Paused --> Running
Running --> Stopped
Stopped --> Removed
Removed --> [*]
Basic Docker Container Commands
Creating and Running Containers
## Pull an image from Docker Hub
docker pull ubuntu:22.04
## Run a new container
docker run -it ubuntu:22.04 /bin/bash
## List running containers
docker ps
## List all containers
docker ps -a
Container Configuration
Containers are defined using Dockerfile, which specifies the base image, environment setup, and application deployment.
Example Dockerfile
## Use official Ubuntu base image
FROM ubuntu:22.04
## Set environment variables
ENV APP_HOME=/app
## Install dependencies
RUN apt-get update && apt-get install -y \
python3 \
python3-pip
## Set working directory
WORKDIR $APP_HOME
## Copy application files
COPY . $APP_HOME
## Install Python dependencies
RUN pip3 install -r requirements.txt
## Expose application port
EXPOSE 8000
## Define startup command
CMD ["python3", "app.py"]
Container Networking
Docker provides multiple networking modes to connect containers:
- Bridge Network (default)
- Host Network
- Overlay Network
- Macvlan Network
Best Practices
- Keep containers small and focused
- Use official base images
- Minimize layer count
- Avoid running containers as root
- Use multi-stage builds
With LabEx, you can practice and explore Docker container management in a hands-on learning environment.