Ansible docker_container Module: Manage Docker Containers (Guide)
By Luca Berton · Published 2024-01-01 · Category: installation
Complete guide to Ansible docker_container module. Create, start, stop, remove Docker containers, manage volumes, networks, environment variables, and implement container orchestration with practical examples.
The community.docker.docker_container module manages Docker containers through Ansible — create, start, stop, restart, remove, and configure containers declaratively. Combined with docker_image and docker_network, it provides complete Docker automation without writing Dockerfiles or shell scripts.
Prerequisites
Basic Container Operations
Create and Start a Container
Stop a Container
Remove a Container
Restart a Container
Container Configuration
Environment Variables
Volumes
Networks
Resource Limits
Health Checks
Restart Policy
Labels
Multi-Container Application
Docker Compose with Ansible
Image Management
FAQ
How do I manage Docker containers with Ansible?
Install the community.docker collection and use docker_container module. Set name, image, and state (started/stopped/absent). The module handles creation, starting, stopping, and removal declaratively.
What is the difference between docker_container and docker_compose?
docker_container manages individual containers. docker_compose_v2 manages multi-container applications defined in docker-compose.yml files. Use docker_container for fine-grained control; use docker_compose_v2 when you have existing compose files.
How do I update a container to a new image version?
Set pull: true and change the image tag. The module detects the image change and recreates the container automatically: image: myapp:2.1.0 with pull: true.
Do I need Docker SDK for Python?
Yes, the docker Python package must be installed on the target host (or the controller for local containers): pip install docker.
How do I pass secrets to Docker containers?
Use Ansible Vault to encrypt variables, then pass them via the env parameter: env: SECRET_KEY: "{{ vault_secret }}". Never hardcode secrets in playbooks.
Conclusion
The community.docker collection provides complete Docker management: • docker_container — Create, start, stop, remove containers • docker_image — Pull, build, manage images • docker_network — Create custom networks • docker_volume — Manage persistent storage • docker_compose_v2 — Manage compose stacks
Related Articles • Ansible with Podman: Manage Containers • Ansible Kubernetes Module Guide • Ansible Collections: Install, Use & Create
Category: installation