How to Build a Docker Image from a Batch Script
Packaging an application, whether it's a simple HTML site or a complex Python backend, into a Docker Image ensures that it runs consistently anywhere. While Dockerfiles provide the blueprint, executing the build process consistently (tagging branches, cleaning old images, assigning build arguments) is best handled by an automation script.
In this guide, we will demonstrate how to automate the docker build process using a Batch script.
The Strategy: The docker build Command
- Ensure you have a
Dockerfilein your working directory. - Assign dynamic variables (like the current Date, Username, or Git Commit hash) to tag the image properly.
- Use the
docker buildcommand to compile the image. - Optionally push it to a secure registry.
Setup: A Sample Dockerfile
To test the script, place a simple Dockerfile in the same directory as your .bat file:
# Simple Nginx Server
FROM nginx:alpine
COPY ./html /usr/share/nginx/html
EXPOSE 80
Also, create a subfolder named html with a basic index.html inside it.
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
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 Image Details
set "registry=mycompany.azurecr.io"
set "repo=webapp-frontend"
:: Generate a dynamic tag based on the current date/time
for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /value') do set "dt=%%I"
set "tag=!dt:~0,8!-!dt:~8,4!"
:: Full image name
set "imageName=%registry%/%repo%:!tag!"
set "latestName=%registry%/%repo%:latest"
echo.
echo --- DOCKER BUILD PROCESS ---
echo Building Image: !imageName!
echo Working Directory: %CD%
echo.
:: 4. Verify Dockerfile exists
if not exist "Dockerfile" (
echo [ERROR] No Dockerfile found in "%CD%".
pause
exit /b 1
)
:: 5. Execute Build Command
:: -t tags the image
:: . specifies the current directory as the build context
docker build -t "!imageName!" -t "%latestName%" .
:: Capture the exit code immediately
set "buildResult=!errorlevel!"
if !buildResult! neq 0 (
echo.
echo [ERROR] Docker build failed with exit code !buildResult!. Inspect the logs above.
pause
exit /b 1
)
echo.
echo ==========================================
echo BUILD SUCCESSFUL
echo Tags:
echo - !imageName!
echo - %latestName%
echo ==========================================
:: 6. Optional: Push to Registry
echo.
set /p "push=Push image to registry? (Y/N): "
if /i "!push!"=="Y" (
echo Pushing !imageName!...
docker push "!imageName!"
if !errorlevel! neq 0 (
echo [ERROR] Failed to push !imageName!. Are you logged in to the registry?
pause
exit /b 1
)
docker push "%latestName%"
if !errorlevel! neq 0 (
echo [ERROR] Failed to push %latestName%. Are you logged in to the registry?
pause
exit /b 1
)
echo [SUCCESS] Push complete.
) else (
echo [SKIP] Skipping push to registry.
)
endlocal
pause
exit /b 0
Passing Build Arguments
If your Dockerfile contains ARG instructions (e.g., dynamically setting the base image version or injecting an API endpoint at build time), you can pass them from Batch using --build-arg:
@echo off
setlocal enabledelayedexpansion
set "appVersion=2.4.1"
set "nodeVersion=18-alpine"
:: Verify Docker Daemon is Running
docker info >nul 2>nul
if !errorlevel! neq 0 (
echo [ERROR] Docker is not running or not accessible.
pause
exit /b 1
)
:: Verify Dockerfile exists
if not exist "Dockerfile" (
echo [ERROR] No Dockerfile found in "%CD%".
pause
exit /b 1
)
echo Building my-node-app:%appVersion%...
docker build -t "my-node-app:%appVersion%" --build-arg NODE_VER="%nodeVersion%" .
:: Capture the exit code immediately
set "buildResult=!errorlevel!"
if !buildResult! neq 0 (
echo [ERROR] Docker build failed with exit code !buildResult!.
pause
exit /b 1
)
echo [SUCCESS] Image my-node-app:%appVersion% built successfully.
endlocal
pause
exit /b 0
Why Build Docker Images from Batch?
- CI/CD Precursors: Before setting up complex Jenkins or GitHub Actions pipelines, a simple
build.batscript allows local developers to compile identical Docker images using the exact same tags and arguments. - Nightly Snapshotting: Creating a Windows Scheduled Task that builds the daily code pull, tags it with a timestamp (
20241014-0800), and pushes it to an internal QA registry overnight. - Cross-Platform Consistency: Removing user error when manually typing complex build arguments or registry paths.
Important Considerations
- Build Context: The period
.at the end of thedocker buildcommand tells Docker to send everything in the current directory (the "Context") to the Docker daemon. If your directory is 20 GB of raw data and videos, the build will stall for minutes. Always use a.dockerignorefile in production. - Authentication: The script will fail during the
docker pushstep if it is not already authenticated to the target registry (mycompany.azurecr.io). A preliminarydocker logincommand should be performed locally. - Local Daemon Logs: On Windows,
docker buildoutputs detailed streaming logs by default. If your script freezes or returns an error, examine the nativeDockerfilesteps.
Conclusion
Automating raw Docker builds with a Batch script dramatically speeds up local application development. By dynamically generating distinct tags, integrating build arguments natively, and wrapping the entire CI process behind a double-click .bat file, you create a seamless container compilation pipeline that developers can run locally, continuously, and securely.