DevOps
How to Run Network Automation in Docker: Ansible and Netmiko
Build one Docker image with Python, ansible-core and Netmiko, mount your playbooks and keys, and run device automation the same way on any laptop or CI runner.

Build a small image from python:3.11-slim that installs ansible-core, netmiko, paramiko and openssh-client. Run your scripts and playbooks inside it with your repo bind-mounted and your SSH agent forwarded. You get one toolchain that behaves the same on a laptop, a lab VM and a CI runner. The setup is a Dockerfile, a requirements.txt and one docker run command.
Key takeaways
- Pin Python, ansible-core and Netmiko once in an image and every engineer and pipeline runs the same toolchain.
- Use a two-stage build, a non-root user and a version tag. Never copy SSH keys or credentials into the image.
- Forward the SSH agent and mount a read-only known_hosts file to avoid host key errors.
- Use --network host or macvlan to reach GNS3, EVE-NG or Containerlab nodes.
- Keep thread counts and Ansible forks modest inside a resource-limited container.
Day 1 - Python for Network Engineers | Cisco Devnet
Why run Netmiko and Ansible inside a Docker container instead of your laptop?
Because you pin Python and library versions once, and version conflicts between projects and between engineers on the same team disappear. The image becomes the shared artifact: the same one runs on a workstation, a jump host and a pipeline runner.
Host installs break in two familiar ways. One project needs a newer ansible-core or Paramiko than another, or a laptop OS upgrade wipes your site-packages. A virtualenv fixes the first problem but only isolates Python packages. It does not control OS libraries such as openssh-client, gcc or libffi.
Be honest about the trade-off. If you are one engineer running two scripts a week, a virtualenv is lighter and perfectly fine. Docker pays off when the team grows or CI enters the picture. If you want the full path, the Network Automation Master Program covers Python, Ansible and pipelines in live labs.
| Approach | Isolation | OS library control | Reproducible across team | Best fit |
|---|---|---|---|---|
| Host install | None | No | Poor | Quick one-off test |
| Virtualenv | Python packages | No | Moderate | Solo engineer, few scripts |
| Docker container | Python and OS layer | Yes | Strong | Teams and CI pipelines |
What should a production-ready Dockerfile look like for network automation?
Use a two-stage build: a builder stage that compiles wheels, then a slim runtime that copies only the installed packages. That strips compilers and headers out of the image you actually ship. If you are new to the tool, the Docker course covers images and layers from scratch.
FROM python:3.11-slim AS builder
RUN apt-get update && apt-get install -y --no-install-recommends \
gcc make libffi-dev libssl-dev
COPY requirements.txt requirements.yml /tmp/
RUN pip install --no-cache-dir --prefix=/install -r /tmp/requirements.txt
FROM python:3.11-slim
RUN apt-get update && apt-get install -y --no-install-recommends \
openssh-client ca-certificates && rm -rf /var/lib/apt/lists/*
COPY --from=builder /install /usr/local
COPY requirements.yml /tmp/
RUN ansible-galaxy collection install -r /tmp/requirements.yml \
-p /usr/share/ansible/collections
RUN useradd -m netauto
USER netauto
WORKDIR /workYour requirements.txt holds ansible-core, netmiko, paramiko, scp and pyyaml. Use ansible-core rather than full ansible to keep the image small. Vendor collections for Cisco IOS-XE, NX-OS, Arista EOS and Juniper Junos go in requirements.yml and install with ansible-galaxy, pinned to versions.
| Instruction | Why it is there | Stage |
|---|---|---|
| gcc, make, libffi-dev, libssl-dev | Compile wheels | Builder |
| openssh-client, ca-certificates | ssh, scp and TLS trust | Runtime |
| useradd and USER | Run as non-root | Runtime |
| WORKDIR /work | Predictable relative paths | Runtime |
Build it with docker build -t nk-automation:1.0 .. Tag a version instead of relying on latest. Then a rollback is just running the previous tag, and a teammate's run matches yours. Never COPY SSH keys or credentials into the image: every layer is readable by anyone who pulls it.
How do you build the image and mount your playbooks and scripts?
Keep your code outside the image and bind-mount it at run time. A simple layout works well:
Dockerfile,requirements.txt,requirements.ymlinventory.iniplaybooks/andscripts/backups/for output
For a lab session, run an interactive shell:
docker run --rm -it -v $(pwd):/work -w /work nk-automation:1.0 bashOnce things work, switch to one-shot commands:
docker run --rm -v $(pwd):/work -w /work nk-automation:1.0 \
ansible-playbook -i inventory.ini playbooks/site.yml
docker run --rm -v $(pwd):/work -w /work nk-automation:1.0 \
python scripts/backup_configs.pyThe -w /work flag matters. Forget it and relative paths such as backups/r1.cfg or inventory.ini break, which is the most common student mistake in this setup. Because the whole repo is mounted, Netmiko backups and Ansible logs land on your host and survive --rm. If a write fails, check that the mounted folder is writable by the container user. A refresher on flags is in our guide to the top Docker commands.
How do you pass SSH keys and switch credentials into the container safely?
For interactive work, forward your SSH agent instead of copying keys. Mount the socket and a read-only known_hosts file:
docker run --rm -it -v $(pwd):/work -w /work \
-v $SSH_AUTH_SOCK:/ssh-agent -e SSH_AUTH_SOCK=/ssh-agent \
-v $HOME/.ssh/known_hosts:/home/netauto/.ssh/known_hosts:ro \
nk-automation:1.0 bashIn pipelines, mount the key as a read-only bind mount or a Docker secret, and inject it at run time. Keep switch passwords in environment variables or an Ansible Vault file. Never put them in inventory.ini or Python source.
If you see Host key verification failed, the container does not know the device's key. Mount a known_hosts file and set your host key policy explicitly: Netmiko's ssh_strict option, and the matching SSH connection option or ssh_args in ansible.cfg for Ansible.
Disabling host key checking globally is tempting. In an isolated lab it is acceptable. Against production devices it is bad practice, because it removes your protection against a spoofed device.
How does the container reach switches in GNS3, EVE-NG or Containerlab?
The container needs a route to the lab management network. Outbound SSH does not need published ports, so reachability is what matters.
| Option | How it works | Right call when |
|---|---|---|
| Bridge (default) | NAT through the host | Devices are reachable over routed IP |
| --network host | Shares the host network stack | Container runs on the same host as the lab or management bridge |
| macvlan | Container gets an address on the lab subnet | You need the runner in the same subnet as the nodes, such as Containerlab |
On Linux, --network host is the least friction option. For Containerlab, attach the container to the lab management network or use macvlan.
Before blaming the playbook, test from inside the container:
docker run --rm -it nk-automation:1.0 bash
ping -c 3 10.10.10.11
ssh -v netauto@10.10.10.11If ping or the SSH banner fails here, the problem is networking, not Ansible. You can practise this on our hands-on networking labs.
Netmiko script or Ansible playbook: which do you run in the container?
Use Netmiko for gathering, parsing and backups. Use Ansible for repeatable, idempotent changes across many devices. Both live happily in the same repo and image. If your Python is shaky, start with the Python for network engineers course.
| Netmiko | Ansible | |
|---|---|---|
| Typical use | Backups, show commands, structured checks | Config pushes with reporting |
| Concurrency | ThreadPoolExecutor, you control it | The forks setting |
| Idempotency | You code it | Built into most modules |
| Learning curve | Needs Python | YAML and modules |
Watch concurrency. Forty threads inside a container capped at half a CPU run slower than ten, and many devices limit simultaneous SSH sessions anyway. Raise the container's CPU and memory limits before you raise threads or forks.
Ansible Execution Environments are the vendor-packaged version of the same idea. You can build one that carries custom Python dependencies, including Netmiko, if you include them in the build.
How do you run Dockerized network automation in GitHub Actions or GitLab CI?
Build and tag the image, then run the same tag in the pipeline that you used locally. That is why a passing lab run actually means something. This is the core of network as code.
- Build and tag the image.
- Run a read-only pre-check: back up configs and diff them. Keep the backup as a pipeline artifact.
- Require a manual approval gate before production changes.
- Run the change job.
- Roll back from the saved backup if post-checks fail.
Store SSH keys and device credentials as pipeline secrets, injected at run time and never committed. Runners also need a path to device management IPs, which usually means a self-hosted runner inside the management network. GitHub and GitLab hosted and self-hosted runners work worldwide, so the same Dockerfile and repo work in any region.
Which certifications and skills prove you can do this?
Two vendor exams map well to this work, and the Network Automation Master Program prepares you for the skills behind both.
| Item | Figure | Source |
|---|---|---|
| Cisco 200-901 CCNAAUTO | 120 minutes, $300 USD | Cisco |
| Red Hat EX374 | Hands-on, performance-based exam | Red Hat |
| US median wage, network and computer systems administrators (May 2025) | $99,130 | U.S. BLS |
| US median wage, computer network architects (May 2025) | $134,050 | U.S. BLS |
The wage figures are US data, not global. Check the vendor's booking page for local pricing and exam delivery in your country, and look at local job listings and national statistics for pay where you live.
Employers look for Python, Git, Linux, SSH, YAML and Jinja2, plus one automation framework you have used in anger. Expect interview questions like these:
- Why containerize automation?
- How do you keep secrets out of images?
- How do you roll back a bad push?
- How do you test a playbook before production?
Frequently asked questions
Can I run Ansible Automation Platform execution environments with my own Netmiko scripts?
Yes. An execution environment is a container image, so you can build one that includes Netmiko and its dependencies. Add Netmiko to the image's Python requirements during the build and your playbooks can call it.
How do I keep Netmiko configuration backups after the container stops?
Bind-mount a host folder, for example -v $(pwd):/work, and write backups to a path under it. Files saved there persist after --rm removes the container. Check the folder is writable by the container user.
How do I fix Host key verification failed when Netmiko connects from a container?
Mount a known_hosts file read-only into the container so it recognises the device keys. Then set the host key policy explicitly. Disable checking only in an isolated lab, never against production devices.
Do I need Docker Desktop or is Docker Engine enough for network automation?
Docker Engine is enough on Linux, which suits lab VMs and CI runners. Docker Desktop mainly adds a convenient setup on Windows and macOS. The same image runs on either, so use whichever your machine supports.
Should I use host networking or bridge networking when automating devices from Docker?
Use host networking when the container runs on the same Linux host as your lab and you want direct access to management IPs. Bridge works when devices are reachable by routed IP. Outbound SSH needs no published ports.
Can I run this setup on Windows or macOS, and does it work the same on a Linux runner?
Yes, the image is the same everywhere. Host networking and SSH agent socket mounting behave differently on Windows and macOS, so lab connectivity may need extra setup. On a Linux runner it works as described here.
Practice this in a real lab
Try a lab or start with NKFLIX Starter Courses before you decide.
Learn this live in the AI-Ready DevOps Master Program
Live classes with engineers from top companies, 24x7 labs and a counsellor to plan your path.
Sources and further reading
- Cisco 200-901 CCNAAUTO (formerly DEVASC / Cisco Certified DevNet Associate) exam
- The Red Hat Certified Specialist in Developing Automation with Ansible Automatio
- The median annual wage for Network and Computer Systems Administrators was $99,1
- The median annual wage for Computer Network Architects was $134,050 in May 2025
- Network Kings on YouTube: Day 1 - Python for Network Engineers / Cisco Devnet
