How to Secure Docker Container: Best Practices and Examples
To secure a
Docker container, use minimal base images, run containers as non-root users, and scan images for vulnerabilities. Also, limit container capabilities and use Docker's security options like --read-only and seccomp profiles to reduce attack surface.Syntax
Here are key Docker run options to enhance container security:
--user: Runs container as a specific user instead of root.--read-only: Makes the container filesystem read-only.--cap-drop: Removes Linux capabilities to limit privileges.--security-opt: Applies security profiles like seccomp or AppArmor.
bash
docker run --user 1000 --read-only --cap-drop ALL --security-opt seccomp=default.json myimage
Example
This example runs a Docker container securely by using a non-root user, dropping all capabilities, and making the filesystem read-only.
bash
docker run --rm \ --user 1000 \ --read-only \ --cap-drop ALL \ --security-opt seccomp=default.json \ alpine:3.18 \ sh -c "id && touch /tmp/testfile"
Output
uid=1000 gid=1000 groups=1000
sh: can't create /tmp/testfile: Read-only file system
Common Pitfalls
Common mistakes when securing Docker containers include:
- Running containers as root, which increases risk if compromised.
- Using large or outdated base images that contain vulnerabilities.
- Not scanning images for known security issues.
- Giving containers unnecessary Linux capabilities.
Always verify user permissions and limit capabilities.
bash
docker run --rm alpine:3.18 sh -c "id" # Wrong: runs as root (uid=0) # Correct: docker run --rm --user 1000 alpine:3.18 sh -c "id"
Output
uid=0(root) gid=0(root) groups=0(root)
uid=1000 gid=1000 groups=1000
Quick Reference
Summary of key Docker security options:
| Option | Purpose |
|---|---|
| --user | Run container as non-root user |
| --read-only | Make container filesystem read-only |
| --cap-drop | Remove Linux capabilities |
| --security-opt | Apply security profiles like seccomp |
| Use minimal base images | Reduce attack surface |
| Scan images | Detect vulnerabilities before use |
Key Takeaways
Always run Docker containers as non-root users to reduce risk.
Use minimal and updated base images to avoid vulnerabilities.
Limit container privileges by dropping unnecessary capabilities.
Make container filesystems read-only when possible.
Scan images regularly for security issues before deployment.