Automate Docker Container Management with PowerShell Scripting

Docker containers provide a convenient way to package and isolate applications into standardized units for development, shipping and deployment.

PowerShell offers a powerful scripting environment on Windows to tap into the Docker API and automate various container management tasks. With some PowerShell knowledge and scripting, you can programmatically control Docker containers to build scalable and robust container workflows.

In this comprehensive guide, you will learn:

  • The basics of PowerShell and how it allows automating Docker
  • Key PowerShell modules to manage Docker containers and images
  • How to leverage PowerShell to start, stop and manage Docker containers
  • Techniques to build, tag, push, and distribute Docker images via PowerShell
  • How to use PowerShell scripts to orchestrate multi-container and distributed applications
  • PowerShell tips and tricks for debugging and handling errors with Docker
  • How PowerShell complements Docker Compose and Kubernetes for declarative container orchestration

Follow along to see how PowerShell scripting can help simplify and streamline your container workflows.

Why Automate Docker with PowerShell?

Docker provides a CLI and API to manage containerized processes on a single host. But running repetitive Docker commands manually can be tedious.

PowerShell is a cross-platform automation engine with comprehensive capabilities including:

  • Strong CLI tooling via pwsh and cmdlets
  • A rich object pipeline for composable commands
  • Idempotent resource management via Desired State Configuration
  • Robust remote management and CIM integrations

By leveraging PowerShell to tap into the Docker API and CLI, you gain a flexible and consistent way to script and automate container management operations across hosts.

Key reasons to automate Docker with PowerShell include:

Rapid Provisioning

Quickly stand up or teardown containers without manual CLI calls.

Repeatable Deployments

Reliably release new container versions and promotions across environments.

Scalable Orchestration

Coordinate and schedule distributed applications and microservices.

Portable Scripts

Containerize PowerShell scripts for easy sharing and execution in containers.

Low Overhead

Small resource footprint compared to full orchestrators.

For ad hoc container automation tasks, PowerShell delivers a quick and lightweight scripting solution.

Next let’s look at the key components for getting started with Docker and PowerShell.

Prerequisites for Docker and PowerShell

To follow along with the Docker and PowerShell examples, you will need:

  • Windows 10/Windows Server 2016+ – Modern Windows versions include Hyper-V isolation and client Docker APIs
  • Docker Engine – The Docker service for managing containers
  • PowerShell 5.1+ – Provides Docker cmdlets and CIM integration
  • PSModules – DockerMsftProvider and Posh-Docker PowerShell modules

You can install the Docker Engine via Docker Desktop on Windows 10 or the Docker install package on Windows Server.

PowerShell 5.1 and above are included in modern Windows releases. The PowerShell modules are available via the PowerShell Gallery.

With these components installed, you are ready to dive in!

Key Docker PowerShell Modules

These two free and open-source PowerShell modules provide the necessary cmdlets for scripting Docker:

DockerMsftProvider

This module from Microsoft includes fundamental Docker cmdlets like:

  • Get-DockerContainer
  • Start-DockerContainer
  • Stop-DockerContainer
  • Remove-DockerContainer

It allows core container lifecycle automation using native PowerShell techniques.

Posh-Docker

This popular third-party module from Brandon Olin expands on the capabilities by adding functions like:

  • New-DockerImage
  • Push-DockerImage
  • Save-DockerImage
  • Invoke-DockerContainer

It includes more conveniences for building and distributing Docker images.

Together these modules provide a robust set of tools for Docker automation from PowerShell. Now let’s see them in action.

Managing Docker Containers with PowerShell

Perhaps the most common need is to manage Docker containers programmatically with PowerShell.

The DockerMsftProvider module exposes Docker containers as PowerShell objects, enabling neat control over the container lifecycle.

Listing Containers

To begin, you can view configured containers using Get-DockerContainer:

# List all containers
Get-DockerContainer

# List running containers
Get-DockerContainer -State Running

This outputs a rich object with properties like container ID, image, state, ports, and more.

Starting and Stopping

You can start and stop existing containers easily:

# Start a container
Start-DockerContainer -Name mysql 

# Stop a running container
Stop-DockerContainer -Name mysql

The -Name parameter identifies containers by their configured name.

Removing Containers

And clean up stopped containers completely with Remove-DockerContainer:

# Remove a container
Remove-DockerContainer -Name oldmysql

This deletes the container configuration so it will not restart.

Calling Container Commands

To execute a command inside a running container, use Invoke-DockerContainer:

# Run ipconfig inside a container
Invoke-DockerContainer -Name webapp { ipconfig }

This opens a PowerShell session in the container to run the given scriptblock.

You now have basic building blocks to script Docker container workflows in PowerShell!

Building Docker Images with PowerShell

In addition to running containers, you’ll often need to build Docker images.

The Posh-Docker module makes this easy via the New-DockerImage function.

For example, to package a simple web server:

# Build a new Docker image
New-DockerImage -Name webapp -Path . 

# Add files and install IIS
Add-Content -Path default.htm -Value "<h1>Hello World!</h1>"
Start-Process C:\windows\system32\Dism.exe -Args '/online /enable-feature /all /featurename:IIS-WebServer /NoRestart'

# Set the entrypoint    
EXPOSE 80
ENTRYPOINT ["C:\Windows\System32\inetsrv\w3wp.exe", "-ap", "http.sys"]

This runs commands inside a Dockerfile context to assemble a custom webapp image.

You can also directly commit changes inside a running container:

# Start container to modify
$container = Start-DockerContainer webapp

# Install app inside container
Invoke-DockerContainer $container {
  Install-WindowsFeature Web-Server
} 

# Commit new image 
$container | Commit-DockerContainer -ImageName webappv2

This builds on top of a base image by installing IIS inside a running container and saving a new image webappv2.

For structured Dockerfile builds, New-DockerImage provides a programmatic way to generate images from PowerShell code.

Pushing Docker Images to a Registry

Once you have Docker images built, you’ll want to distribute them to registries like Docker Hub for deployment.

The Push-DockerImage function handles this by pushing local images up to a Docker registry:

# Build image
New-DockerImage -Name myapp

# Add tags
Tag-DockerImage -Name myapp -Tag v1.0,latest 

# Push to Docker Hub
Push-DockerImage -Name myapp -RegistryNamespace "myDockerID"

This pushes the myapp image to Docker Hub under your account.

You can also work with private registries using the -Registry and -Credential parameters:

# Push to private registry
Push-DockerImage -Name myapp -Registry myregistry.com -Credential (Get-Credential)

Now you can easily push images from PowerShell scripts to Docker registries!

Removing Images and Containers

Over time, unused Docker images and containers can pile up and take up disk space.

You can remove these easily in PowerShell with:

# Remove all stopped containers 
Get-DockerContainer -State Exited,Dead | Remove-DockerContainer 

# Remove unused images
Get-DockerImage | Where { $_.Containers -eq $null } | Remove-DockerImage

This keeps your system tidy by removing unused Docker artifacts.

For more advanced image and container cleanup, use Prune-DockerImage and Prune-DockerContainer.

Executing Multi-Container and Distributed Workflows

So far the examples have focused on individual containers.

But you can also orchestrate multi-container apps and distributed workflows using PowerShell scripts.

For example, a common pattern is defining Docker Compose files to coordinate microservices. Typically you would run docker-compose up manually.

To automate this from PowerShell, you can invoke docker-compose to deploy the defined services:

# Deploy Docker Compose file
Start-Process docker-compose -ArgumentList @('up', '-d') -WorkingDirectory .

# Get container names
$containers = docker-compose ps -q

# Wait for containers to start
docker wait $containers

# Run tests
Invoke-Pester .\tests\

# Stop containers
Start-Process docker-compose -ArgumentList @('down')

This allows programmatically deploying a multi-service application, running integration tests, and tearing it down using a Docker Compose file.

For greater scale, you can build PowerShell scripts to interact with clustered container engines like Kubernetes. The Kubernetes PowerShell module provides cmdlets to invoke kubectl commands to deploy pods and manage clusters.

PowerShell enables gluing together disparate steps into automated distributed workflows driven by code.

Handling Output, Logs and Errors

Careful handling of output, logs, and errors is crucial when scripting Docker interactions.

Capturing Output

Many key Docker and PowerShell commands produce useful output that you’ll want to inspect or store.

For example, you can capture Docker container logs using PowerShell redirection:

# Start container
$container = Start-DockerContainer webapp 

# Stream logs
docker logs $container.ID 2>&1 | Tee-Object -FilePath .\logs.txt

This pipes container stdout/stderr into a log file for later review.

Trapping Errors

To handle failures in PowerShell scripts, use Try/Catch blocks:

Try {
  Start-DockerContainer test
}
Catch [exception] {
  Write-Error "Container failed to start!" 
  exit 1
}

This catches Docker start failures and lets you handle them appropriately, such as retry logic or alerting.

Parsing Command Output

You can parse text output using PowerShell operators like -split and -match to extract values:

$output = docker ps
$container = $output -match "myapp\s+.*Up"
$id = $container -split '\s+' | Select-Object -First 1

This parses a Docker PS call to grab the ID of a named container when scripting.

Centralized Logging

For managing logs across multiple servers, use centralized logging tools like the ELK stack. Stream Docker logs to Logstash or ingest PowerShell transcipts for unified access.

Robust logging and error handling is key for maintaining and troubleshooting large-scale scripted container deployments.

Integrating with Docker Compose and Kubernetes

PowerShell scripting provides a flexible way to automate individual Docker hosts. But for multi-host deployments, declarative frameworks like Docker Compose and Kubernetes can complement your PowerShell scripts.

Docker Compose

Compose is ideal for defining and running multi-container apps on a single Docker host.

Include a docker-compose.yml file for app services. Then invoke docker-compose from PowerShell to orchestrate the coordinated deployment of your defined services.

Kubernetes

For container orchestration across many hosts, Kubernetes is the leading platform.

You can manage Kubernetes clusters and deployments using the Kubernetes PowerShell module. Or invoke kubectl directly from PowerShell scripts to drive Kubernetes.

PowerShell integrations with Kubernetes tooling like Helm enable fully automated cluster deployments.

Choosing the Right Level of Automation

Consider Docker Compose for simple to moderate container orchestration scenarios, and Kubernetes for advanced or distributed architectures.

PowerShell scripts provide the glue to invoke these tools as needed while offering custom logic around them.

Putting it All Together

Let’s see a complete PowerShell script that implements some best practices:

# Login to Docker registry 
docker login ...

# Wrap in try/catch block
Try {

  # Build image
  New-DockerImage -Name...

  # Tag image
  Tag-DockerImage ...

  # Push image
  Push-DockerImage ...

  # Deploy containers
  Start-DockerCompose ...  

  # Wait for containers 
  Wait-DockerContainer ...

  # Test containers
  Test-ContainerServices

  # Gather logs
  Get-DockerLogs test > logs.txt

} Catch {
  # Handle failures
} Finally {
  # Clean up 
  docker-compose down
}

# Logout of registry
docker logout

This demonstrates:

  • Handling login and logout
  • Wrapping in try/catch blocks
  • Building, tagging and pushing images
  • Deploying and testing containers
  • Capturing logs
  • Cleaning up containers

You can expand on this pattern to build reliable, automated Docker workflows using PowerShell scripts.

PowerShell + Docker = Automation Superpowers

In summary, PowerShell delivers a cross-platform automation solution to script routine Docker operations and augment your container lifecycle management.

Key highlights include:

  • Robust Docker Modules – DockerMsftProvider and Posh-Docker provide needed Docker cmdlets
  • Managing Containers – Control container start, stop, remove, commands
  • Building Images – Assemble Dockerfiles or commit changes
  • Distributing Images – Push to registries like Docker Hub
  • Deploying Compose – Orchestrate multi-container apps
  • Kubernetes Control – Manage Kubernetes through kubectl
  • Error Handling – Trap and handle failures
  • Output Capture – Logging and parsing output
  • Repeatable Infrastructure – Reliable, versioned container workflows

Following Docker best practices like small containers and immutable infrastructure enables efficient containerization.

Combining these patterns with PowerShell scripting delivers a flexible way to automate provisioning, deployment, and DevOps around your Docker environments.

Start scripting your container workflows today to enhance productivity and reliability!

Leave a Comment

Available for Amazon Prime