How to Create Docker Containers with Ansible

Create Docker Containers with Ansible

Ansible simplifies Docker management by automating tasks like container creation, image management, volume configuration, and even network setup. You can ensure consistency, reduce manual errors, and save time while deploying and managing Docker containers using Ansible Docker modules.

In this guide, we’ll learn how to use Ansible to create Docker containers, including setting up Docker, creating playbooks, and managing Docker images.

Step 1: Install Docker Modules

Docker modules for Ansible are part of the community.docker collection, which allows you to manage Docker containers, images, networks, and volumes directly through Ansible playbooks.

1. The community.docker collection relies on the Docker SDK for Python. Install it using pip:

 # pip install docker

2. Install the community.docker collection for managing Docker resources.

 # ansible-galaxy collection install community.docker

This will download and install the community.docker collection into your Ansible environment.

3. Verify the installation.

 # ansible-galaxy collection list

Look for community.docker in the output.

# /home/user/.ansible/collections/ansible_collections
Collection           Version
-------------------- -------
community.docker     1.x.x
ansible.posix        1.x.x

Step 2: Automate Docker Installation (Optional)

If Docker is not installed on your target machine, automate it using an Ansible playbook.

1. Create a playbook named install_docker.yml:

---
- name: Install Docker on Target Machines
  hosts: all
  become: true  # Execute tasks as a superuser
  tasks:
    - name: Update APT repositories
      apt:
        update_cache: yes

    - name: Install prerequisites
      apt:
        name:
          - apt-transport-https
          - ca-certificates
          - curl
          - software-properties-common
        state: present

    - name: Add Docker GPG key
      apt_key:
        url: https://download.docker.com/linux/ubuntu/gpg
        state: present

    - name: Add Docker repository
      apt_repository:
        repo: deb [arch=amd64] https://download.docker.com/linux/ubuntu focal stable
        state: present

    - name: Install Docker
      apt:
        name: docker-ce
        state: present

    - name: Start and enable Docker service
      service:
        name: docker
        state: started
        enabled: yes

Here is a brief explanation of each task:

  • Update APT Repositories: Refreshes package information to fetch the latest Docker versions.
  • Install Prerequisites: Installs tools required for downloading and adding repositories.
  • Add Docker GPG Key: Ensures secure downloads by verifying Docker packages using the apt_key module.
  • Add Repository: Adds the Docker repository to APT sources using the apt_repository module.
  • Install Docker: Install Docker CE using the apt module.
  • Start and Enable Docker: Uses the service module to check  Docker starts automatically after a reboot.

2. Run the playbook by specifying your inventory file.

 # ansible-playbook -i inventory install_docker.yml

3. Verify if Docker is installed and available on the remote nodes:

 # ansible all -i inventory -m shell -a "docker --version"

If Docker is installed on the remote machine, the output will show the installed version:

node1 | SUCCESS | rc=0 >>
Docker version 20.10.8, build 3967b7d

node2 | SUCCESS | rc=0 >>
Docker version 20.10.12, build b732d0c

Step 3: Create Docker Containers with Ansible

In this section, we will show you how to create a Docker container on the remote node with Ansible.

1. Create an inventory file to list all servers you want to manage with Ansible.

[servers]
192.168.1.100 ansible_user=root ansible_ssh_private_key_file=~/.ssh/id_rsa

Here is the explanation:

  • [servers]: A group of target machines.
  • ansible_user: The user used to log into the machine.
  • ansible_ssh_private_key_file: Path to your SSH key for authentication.

2. Create a playbook file named create_docker_containers.yml:

---
- name: Create Docker Containers with Ansible
  hosts: servers
  become: true
  tasks:
    - name: Pull Docker Image
      community.docker.docker_image:
        name: nginx
        tag: latest
        source: pull
      register: image_result 

    - name: Create a Docker Container
      community.docker.docker_container:
        name: nginx_container
        image: nginx:latest
        state: started
        ports:
          - "8080:80"

Here is the explanation of each task:

  • Pull Docker Image: Download the latest NGINX image from Docker Hub to the target server.
  • Create a Docker Container: Creates and starts an NGINX container using the pulled image. Then, binds the host’s port 8080 to the container’s port 80 for external access.

3. Run the playbook:

 # ansible-playbook -i inventory create_docker_containers.yml

Step 4: Verify the Docker Containers

After running the playbook, verify that the container is running on the target server using the ad-hoc command:

 # ansible servers -i inventory -m shell -a "docker ps"

Output.

node1 | SUCCESS | rc=0 >>
CONTAINER ID   IMAGE     COMMAND                  CREATED         STATUS         PORTS               NAMES
abc123456def   nginx     "/docker-entrypoint.…"   5 seconds ago   Up 4 seconds   80/tcp              my_container

Step 5: Access the Running Container

In your browser, navigate to http://192.168.1.100:8080 (replace with the target machine’s IP). You should see the default Nginx welcome page.

Conclusion

Using Ansible Docker modules, you’ve automated the creation and management of Docker containers. This setup eliminates manual intervention, reduces errors, and ensures consistency across deployments. Expand this setup to manage more complex containerized applications and streamline your DevOps workflow.

FAQs

1. How do I stop and remove a Docker container using Ansible?

Use the docker_container module with state: absent to stop and remove a container.

2. Can I use Ansible to manage Docker Compose files?

Yes, Ansible can manage Docker Compose setups using the community.docker.docker_compose module or by running docker-compose commands.

3. How do I manage Docker volumes with Ansible?

Use the docker_volume module to create, inspect, and remove Docker volumes.

4. Can I use Ansible to configure Docker networks?

Yes, the docker_network module allows you to create and manage Docker networks.

About Hitesh Jethva

I am Hitesh Jethva, Founder and Author at Code2DevOps.com. With over 15 years of experience in DevOps and open source technologies, I am passionate about empowering teams through automation, continuous integration, and scalable solutions.

View all posts by Hitesh Jethva