Big IT Day: 3 bonus programs with every master program · ends Mon 7 Dec, 11:59 PM. See the offer

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.

By Network KingsPublished 24 November 20267 min read
How to Run Network Automation in Docker: Ansible and Netmiko

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

In this article

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.

Side-by-side comparison of a virtualenv and a Docker container for Netmiko and Ansible automation, covering isolation, OS libraries, team reproducibility and best fit.
Virtualenv isolates Python packages; Docker also pins the OS layer.

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.

ApproachIsolationOS library controlReproducible across teamBest fit
Host installNoneNoPoorQuick one-off test
VirtualenvPython packagesNoModerateSolo engineer, few scripts
Docker containerPython and OS layerYesStrongTeams 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 /work

Your 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.

InstructionWhy it is thereStage
gcc, make, libffi-dev, libssl-devCompile wheelsBuilder
openssh-client, ca-certificatesssh, scp and TLS trustRuntime
useradd and USERRun as non-rootRuntime
WORKDIR /workPredictable relative pathsRuntime

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.yml
  • inventory.ini
  • playbooks/ and scripts/
  • backups/ for output

For a lab session, run an interactive shell:

docker run --rm -it -v $(pwd):/work -w /work nk-automation:1.0 bash

Once 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.py

The -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 bash

In 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.

OptionHow it worksRight call when
Bridge (default)NAT through the hostDevices are reachable over routed IP
--network hostShares the host network stackContainer runs on the same host as the lab or management bridge
macvlanContainer gets an address on the lab subnetYou 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.11

If 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.

NetmikoAnsible
Typical useBackups, show commands, structured checksConfig pushes with reporting
ConcurrencyThreadPoolExecutor, you control itThe forks setting
IdempotencyYou code itBuilt into most modules
Learning curveNeeds PythonYAML 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.

Five ordered pipeline steps: build and tag the image, run a read-only pre-check with config backup, require manual approval, run the change job, roll back from the saved backup.
Build once, then run the same tag locally and in the pipeline.
  1. Build and tag the image.
  2. Run a read-only pre-check: back up configs and diff them. Keep the backup as a pipeline artifact.
  3. Require a manual approval gate before production changes.
  4. Run the change job.
  5. 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.

ItemFigureSource
Cisco 200-901 CCNAAUTO120 minutes, $300 USDCisco
Red Hat EX374Hands-on, performance-based examRed Hat
US median wage, network and computer systems administrators (May 2025)$99,130U.S. BLS
US median wage, computer network architects (May 2025)$134,050U.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.

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.

Why learn from the top 1% of engineers?

Because passing an exam and doing the job are different skills, and only experience closes the gap. Network Kings mentors have spent 11 to 20+ years building and running networks, cloud platforms and pipelines at companies like Apple, Juniper Networks, IBM and CDAC. They teach what breaks in production, why, and how engineers fix it under pressure.

  • Atul Sharma, Founder & CEO mentor at Network KingsAtul Sharma, Founder & CEO
  • Lazaro (Laz) Diaz, Networking mentor at Network KingsLazaro (Laz) Diaz, Networking
  • Sanjay Sharma, AWS mentor at Network KingsSanjay Sharma, AWS
  • Vikas Kumar, Azure mentor at Network KingsVikas Kumar, Azure
  • Ajay, Azure mentor at Network KingsAjay, Azure
  • Amit Bhatt, Linux & DevOps mentor at Network KingsAmit Bhatt, Linux & DevOps

Atul Sharma (Founder & CEO, 12+ yrs), Lazaro (Networking), Sanjay Sharma (AWS, 20+ yrs) and more. Meet the mentors

Same problem, two answers. Pick a track:

On the job: Two routers' OSPF neighbours are stuck in ExStart and never reach Full.

The textbook answer

OSPF moves through Down, Init, 2-Way, ExStart, Exchange, Loading and Full. Memorise the neighbour states for the exam.

Correct. Not enough to fix it.

How a production engineer teaches it

  1. Suspect an MTU mismatch first. ExStart and Exchange stalls usually come down to it.
  2. Compare show ip ospf interface on both ends and fix the interface MTU.
  3. Use ip ospf mtu-ignore only as a stopgap, and say so in the change record.
  4. Write down why it happened, so the next engineer finds it in minutes.
  • The why behind every command, not just the syntax.
  • Hands-on labs for every topic, so the first fault you fix is not at work.
  • Doubts answered by someone who has fixed it in a live network, cloud or pipeline.