Skip to main content

How to Run a Docker Container from a Batch Script

Docker has fundamentally changed how applications are deployed, allowing you to package an application with its dependencies into a standardized unit called a container. If you have Docker Desktop or the Docker Engine installed on your Windows machine, the docker CLI tool becomes available globally. This allows Batch scripts to instantly spin up, configure, and connect to isolated environments.

In this guide, we will demonstrate how to run Docker containers seamlessly via a Batch script.

The Strategy: The docker run Command

  1. Verify that the docker daemon is running.
  2. Use docker run to pull the image (if not already local) and start the container.
  3. Assign ports, mount volumes, and set environment variables dynamically based on the script's input.
  4. Run it in "Detached" (-d) or "Interactive" (-it) mode.

Setup: Ensure Docker is Running

Before running the core script, ensure the Docker Engine is active. Otherwise, docker pull or run will result in a connection error.

Implementation Script

@echo off
setlocal enabledelayedexpansion

:: 1. Verify Docker is installed
where docker >nul 2>nul
if !errorlevel! neq 0 (
echo [ERROR] Docker is not installed or not in PATH.
pause
exit /b 1
)

:: 2. Verify Docker Daemon is Running
echo Checking Docker Status...
docker info >nul 2>nul
if !errorlevel! neq 0 (
echo [ERROR] Docker is not running or not accessible.
echo Please start Docker Desktop and try again.
pause
exit /b 1
)

:: 3. Define Container Settings
set "imageName=nginx:latest"
set "containerName=my-web-server"
set "hostPort=8080"
set "containerPort=80"
:: Use %CD% for the current script directory in mounts
set "hostVolume=%CD%\html"

:: 4. Create the Local Directory for the Mount (if it doesn't exist)
if not exist "%hostVolume%" (
echo Creating volume directory "%hostVolume%"...
mkdir "%hostVolume%"
echo ^<h1^>Hello from Batch Script!^</h1^> > "%hostVolume%\index.html"
)

:: 5. Stop and Remove any existing container with the same name
echo Checking for old containers...
docker stop "%containerName%" >nul 2>nul
docker rm "%containerName%" >nul 2>nul

:: 6. Run the Docker Container
echo Starting container "%containerName%" using "%imageName%"...
echo Mapping Port: %hostPort% -^> %containerPort%
echo Mounting Volume: "%hostVolume%" -^> /usr/share/nginx/html

:: -d runs in detached mode (background)
:: -p maps the host port to the container port
:: -v mounts the local directory into the container
docker run -d --name "%containerName%" -p "%hostPort%:%containerPort%" -v "%hostVolume%:/usr/share/nginx/html" "%imageName%"

:: Capture the exit code immediately
set "dockerResult=!errorlevel!"

if !dockerResult! neq 0 (
echo.
echo [ERROR] Failed to start container. Exit code: !dockerResult!
pause
exit /b 1
)

echo.
echo ==========================================
echo DOCKER CONTAINER RUNNING!
echo Access the server at: http://localhost:%hostPort%
echo ==========================================

endlocal
pause
exit /b 0

Running Temporary Containers (Interactive)

Sometimes you don't want a long-running web server (-d), but rather an isolated environment to execute a single task or launch an interactive shell.

@echo off
setlocal enabledelayedexpansion

set "image=ubuntu:latest"

:: Verify Docker Daemon is Running
docker info >nul 2>nul
if !errorlevel! neq 0 (
echo [ERROR] Docker is not running or not accessible.
echo Please start Docker Desktop and try again.
pause
exit /b 1
)

echo Launching an interactive Ubuntu shell...
echo Type 'exit' to leave.

:: -it attaches a terminal so you can interact with it
:: --rm automatically deletes the container when you exit
docker run -it --rm "%image%" /bin/bash

:: Capture the exit code immediately
set "dockerResult=!errorlevel!"

echo.
if !dockerResult! equ 0 (
echo Container session ended and removed.
) else (
echo [ERROR] Container exited with code !dockerResult!.
)

endlocal
pause
exit /b 0

Why Run Docker from Batch?

  1. Development Environments: Starting a local PostgreSQL database, Redis cache, and Node.js backend cluster with a single "Start-Dev.bat" script.
  2. Tool Chains: Needing a specific version of Python or FFmpeg for processing a batch of files, but not wanting to install it globally on the host OS. Passing the files into a temporary container (--rm), letting it parse them, and exiting cleanly.
  3. Portability: Shipping a repository that contains run.bat. A developer simply clicks it, and Docker downloads all dependencies and builds the entire software stack.

Important Considerations

  1. Volume Paths: Docker requires absolute paths for volume mounts on Windows. The %CD% variable guarantees the correct directory regardless of where the Batch script is executed from. However, if %CD% contains spaces, you must enclose the entire volume mapping in quotes (-v "%hostVolume%:/app").
  2. Pull Delays: If the image is not available locally, docker run automatically pulls it from Docker Hub. This can pause your script execution for several minutes depending on the connection speed. Add docker pull %imageName% first if you want clearer progress output.
  3. Cross-Platform Constraints: Windows Batch syntax relies heavily on backslashes (\), but Linux containers expect forward slashes (/). Be extra careful when defining the container's internal path (/usr/share/nginx/html).

Conclusion

Running Docker containers bridges the gap between static Windows command-line environments and dynamic, isolated Linux ecosystems. By wrapping docker run inside a Batch script, complete with automatic volume mapping, port assignment, and cleanup logic, you create a one-click deployment experience that delivers complex software stacks consistently across any machine.