AnsiblePilot — Master Ansible Automation

AnsiblePilot is the leading resource for learning Ansible automation, DevOps, and infrastructure as code. Browse over 1,400 tutorials covering Ansible modules, playbooks, roles, collections, and real-world examples. Whether you are a beginner or an experienced engineer, our step-by-step guides help you automate Linux, Windows, cloud, containers, and network infrastructure.

Popular Topics

About Luca Berton

Luca Berton is an Ansible automation expert, author of 8 Ansible books published by Apress and Leanpub including "Ansible for VMware by Examples" and "Ansible for Kubernetes by Example", and creator of the Ansible Pilot YouTube channel. He shares practical automation knowledge through tutorials, books, and video courses to help IT professionals and DevOps engineers master infrastructure automation.

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.

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

# Install the collection
ansible-galaxy collection install community.docker

# Python Docker SDK required on target hosts pip install docker

See also: Ansible Docker: Complete Guide to Container Automation (2026)

Basic Container Operations

Create and Start a Container

- name: Run nginx container
  community.docker.docker_container:
    name: webserver
    image: nginx:latest
    state: started
    ports:
      - "80:80"
      - "443:443"

Stop a Container

- name: Stop nginx
  community.docker.docker_container:
    name: webserver
    state: stopped

Remove a Container

- name: Remove container
  community.docker.docker_container:
    name: webserver
    state: absent

Restart a Container

- name: Restart application
  community.docker.docker_container:
    name: myapp
    state: started
    restart: true

Container Configuration

Environment Variables

- name: Run app with environment variables
  community.docker.docker_container:
    name: myapp
    image: myapp:latest
    state: started
    env:
      DATABASE_URL: "postgresql://db:5432/myapp"
      REDIS_URL: "redis://redis:6379"
      NODE_ENV: "production"
      SECRET_KEY: "{{ vault_secret_key }}"

Volumes

- name: Run with volumes
  community.docker.docker_container:
    name: postgres
    image: postgres:16
    state: started
    volumes:
      - pgdata:/var/lib/postgresql/data        # Named volume
      - /opt/backups:/backups                   # Bind mount
      - /opt/config/pg.conf:/etc/postgresql/postgresql.conf:ro  # Read-only
    env:
      POSTGRES_PASSWORD: "{{ db_password }}"

Networks

- name: Create custom network
  community.docker.docker_network:
    name: app_network
    driver: bridge

- name: Run on custom network community.docker.docker_container: name: myapp image: myapp:latest state: started networks: - name: app_network aliases: - app - backend

Resource Limits

- name: Run with resource limits
  community.docker.docker_container:
    name: myapp
    image: myapp:latest
    state: started
    memory: "512m"
    memory_reservation: "256m"
    cpus: 1.5
    cpu_shares: 512

Health Checks

- name: Run with health check
  community.docker.docker_container:
    name: myapp
    image: myapp:latest
    state: started
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8080/health"]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 40s

Restart Policy

- name: Run with auto-restart
  community.docker.docker_container:
    name: myapp
    image: myapp:latest
    state: started
    restart_policy: unless-stopped
    # Options: no, on-failure, always, unless-stopped

Labels

- name: Run with labels
  community.docker.docker_container:
    name: myapp
    image: myapp:latest
    state: started
    labels:
      app: myapp
      environment: production
      managed_by: ansible
      traefik.enable: "true"
      traefik.http.routers.myapp.rule: "Host(`app.example.com`)"

See also: community.docker 5.1.0 — New Feature for Docker Compose Pull

Multi-Container Application

---
- name: Deploy application stack
  hosts: docker_hosts
  become: true
  vars:
    app_version: "2.1.0"

tasks: - name: Create application network community.docker.docker_network: name: app_net

- name: Create data volumes community.docker.docker_volume: name: "{{ item }}" loop: - pgdata - redis_data

- name: Run PostgreSQL community.docker.docker_container: name: db image: postgres:16 state: started restart_policy: unless-stopped networks: - name: app_net volumes: - pgdata:/var/lib/postgresql/data env: POSTGRES_DB: myapp POSTGRES_USER: myapp POSTGRES_PASSWORD: "{{ vault_db_password }}"

- name: Run Redis community.docker.docker_container: name: redis image: redis:7-alpine state: started restart_policy: unless-stopped networks: - name: app_net volumes: - redis_data:/data

- name: Run application community.docker.docker_container: name: myapp image: "myapp:{{ app_version }}" state: started restart_policy: unless-stopped pull: true networks: - name: app_net ports: - "8080:8080" env: DATABASE_URL: "postgresql://myapp:{{ vault_db_password }}@db:5432/myapp" REDIS_URL: "redis://redis:6379" healthcheck: test: ["CMD", "curl", "-f", "http://localhost:8080/health"] interval: 30s timeout: 10s retries: 3

Docker Compose with Ansible

# Use community.docker.docker_compose_v2 for docker compose files
- name: Deploy with docker compose
  community.docker.docker_compose_v2:
    project_src: /opt/myapp
    state: present
    # Reads docker-compose.yml from project_src

- name: Stop compose stack community.docker.docker_compose_v2: project_src: /opt/myapp state: absent

See also: Ansible Molecule Docker: Test Roles in Containers (Guide)

Image Management

- name: Pull latest image
  community.docker.docker_image:
    name: myapp
    tag: latest
    source: pull

- name: Build from Dockerfile community.docker.docker_image: name: myapp tag: "{{ version }}" source: build build: path: /opt/myapp dockerfile: Dockerfile

- name: Remove old images community.docker.docker_prune: images: true images_filters: dangling: true

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 ContainersAnsible Kubernetes Module GuideAnsible Collections: Install, Use & Create

Category: installation

Browse all Ansible tutorials · AnsiblePilot Home