Container Operations¶
Prerequisites¶
- Docker installed and running
- User added to docker group
Procedure: Pull and Run a Container¶
When to use: Launching a new application instance.
Steps:
-
Pull image:
docker pull nginx:latest -
Run container (background mode):
docker run -d --name my-nginx -p 8080:80 nginx:latest -
Verify:
docker ps
Troubleshooting:
- "Bind for 0.0.0.0:8080 failed: port is already allocated": Choose a different host port (e.g.,
-p 8081:80).
Procedure: Build an Image from a Dockerfile¶
When to use: Creating a custom image with your application code.
Steps:
-
Create
Dockerfile:FROM python:3.9 COPY . /app WORKDIR /app RUN pip install -r requirements.txt CMD ["python", "app.py"] -
Build image:
docker build -t myapp:v1 .
Troubleshooting:
- "COPY failed": Ensure source files exist in the build context (directory where you run build).
Procedure: Inspect a Running Container¶
When to use: Debugging configuration or networking issues.
Steps:
-
View JSON metadata:
docker inspect my-nginx -
Filter specific info (e.g., IP address):
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' my-nginx
Troubleshooting:
- "No such object": Check container name with
docker ps -a.
Procedure: View Container Logs¶
When to use: Application is crashing or behaving incorrectly.
Steps:
-
View all logs:
docker logs my-nginx -
Follow logs in real-time:
docker logs -f my-nginx
Troubleshooting:
- Logs are empty: Ensure application writes to stdout/stderr, not a file.
Procedure: Execute a Command Inside a Container¶
When to use: Manual troubleshooting, checking files, or database administration inside a container.
Steps:
-
Open a shell:
(Usedocker exec -it my-nginx /bin/bash/bin/shif bash is not available, e.g., Alpine images) -
Run a single command:
docker exec my-nginx cat /etc/nginx/nginx.conf
Troubleshooting:
- "exec failed": The container might be stopped or crashing.
Procedure: Publish a Container Port¶
When to use: Exposing an internal service to the host network.
Steps:
-
Map port at runtime:
docker run -p <host_port>:<container_port> <image> -
Example (Host 8080 -> Container 80):
docker run -p 8080:80 nginx
Troubleshooting:
- Service unreachable: Check host firewall and ensure container is listening on
0.0.0.0, not127.0.0.1.
Procedure: Scan an Image for Vulnerabilities¶
When to use: Security auditing before deployment.
Steps:
-
Use Trivy (if installed):
trivy image myapp:v1 -
Or Docker Scan (if available):
docker scan myapp:v1
Troubleshooting:
- "Command not found": Install Trivy or enable Docker Scan plugin.
Quick Reference¶
| Action | Command |
|---|---|
| Run | docker run -d -p 80:80 image |
| List Running | docker ps |
| List All | docker ps -a |
| Logs | docker logs <id> |
| Shell | docker exec -it <id> sh |
| Stop | docker stop <id> |
| Remove | docker rm <id> |
| Build | docker build -t name . |
| Prune (Clean) | docker system prune |
Related Documentation¶
- Technologies: Docker
- Concepts: Containers