Docker
Key Docker Instructions
FROM
: Set base image
RUN
: Executes a command in a new layer
COPY
: Copy files and directories from build context into container
ADD
: Similar as COPY with added extract feature
ENV
: Set environment variables
EXPOSE
: Inform docker which port to listen
ENTRYPOINT
: Configure container to be executable
CMD
: Specifies a default command when container started
VOLUME
: Create a mount point for external storage volume
WORKDIR
: Set the working directory for subsequent command
Best Practices
- Use minial base images
- Use multi-stage builds
- Reduce layers. Combining command to reduce number of layer
- Optimize layer caching. Order least change command at the top
- Delete log, temporary files and caches to reduce image size
- Never include sensitive data (password, API key)
- Use
.dockerignore
- Run non-root user
- Scan for vulnerabilities. Use Trivy
Example Dockerfile
FROM nginx:latest
COPY ./webapp /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
# Example 2
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
USER appuser
Command
docker run
docker build
docker pull
docker push
docker image
: List all local docker image
docker ps
docker stop
docker rm
: Remove docker container
docker rmi
: Remove docker image
docker exec
docker logs
docker compose
CMD vs ENTRYPOINT
entrypoint |
CMD |
Set fixed command when container start |
Set default command/argument |
Append argument at runtime |
Can overridden at runtime |
FROM alpine:latest
ENTRYPOINT ["ls"]
CMD ["-alh"]
ADD vs COPY
COPY |
ADD |
Copy files and directories to docker image |
Same as Copy with additional extract compressed files and copy files from remote via URL |
Advantage of Docker
- Portability: Containers run consistently across different environments
- Efficiency: Lightweight compared to virtual machines, saving system resources
- Isolation: Containers are isolated, reducing conflicts between applications
- Scalability: Easy to scale and distribute containerized applications
- Rapid Deployment: Quick to build and deploy applications
- Version Control and Reusability: Facilitates version control and reuse of container images
- Simplified Configuration: Simplifies the setup and configuration of applications
Disadvantage of Docker
- Security Concerns: Containers share the host OS kernel, potentially leading to security vulnerabilities
- Complexity: Managing and orchestrating numerous containers can be complex
- Persistent Storage: Managing data persistence for containers can be challenging
- Performance Overhead: Some performance overhead, especially in high-density environments
- Compatibility: Not all applications are suitable for containerization
- Learning Curve: Requires learning new tools and concepts