Use Simple Shell Scripts to Automate Docker: Start, Check, and Update Containers with Ease
Using Docker makes running apps easier, but some tasks—like starting containers, watching logs, or updating images can feel repetitive. Luckily, shell scripts can handle these tasks automatically, saving you time. In this guide, we’ll review a few easy-to-follow scripts that anyone can use, even if you’re new to scripting or Docker.
These scripts can:
Start containers with one command
Check logs as they happen
Update images without all the usual steps
Each example is explained simply, so let’s jump in and make Docker work for you.
1. Starting a Docker Container with a Shell Script
Manually typing out commands to start a container is time-consuming. This short script does it for you.
#!/bin/bash
if [ -z "$1" ]; then
echo "Please provide a container name."
exit 1
fi
docker run -d --name "$1" nginx
echo "Started container named '$1'."
How It Works:
-d
means the container will run in the background.--name "$1"
sets the container’s name to whatever you type after the script name.
Example: Running ./start_
container.sh
myapp
will start a new container called “myapp.”
2. Watching Logs with a Simple Script
Seeing logs in real time helps keep track of what’s happening inside your app. This script does that.
#!/bin/bash
if [ -z "$1" ]; then
echo "Please provide a container name."
exit 1
fi
docker logs -f "$1"
How It Works:
-f
tells Docker to follow the logs, so new updates appear live.
Example: If you start your container and then run ./watch_
logs.sh
myapp
, you’ll see all the new log entries as they come in.
3. Updating a Docker Container Image
To keep a container updated with the latest version, use this script. It pulls the latest image, stops and removes the old container, then starts a new one.
#!/bin/bash
if [ -z "$1" ]; then
echo "Please provide a container name."
exit 1
fi
docker pull "$1"
docker stop "$1"
docker rm "$1"
docker run -d --name "$1" "$1"
echo "Updated and restarted container '$1'."
How It Works:
docker pull
downloads the latest version of the image.docker stop
anddocker rm
shut down and remove the old container.docker run -d --name "$1" "$1"
starts a new container with the updated image.
Example: Running ./update_
image.sh
myapp
will refresh the container to the latest version of “myapp.”
Why These Scripts Help
Imagine you want to update your web app and check that it runs smoothly afterward. You could combine the update and log scripts like this:
#!/bin/bash
./update_image.sh myapp
./watch_logs.sh myapp
This way, you only need to run one command to get the latest version up and watch for any issues in real-time.
Subscribe to my newsletter
Read articles from Chetan Mohanrao Mohod directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Chetan Mohanrao Mohod
Chetan Mohanrao Mohod
DevOps Engineer focused on automating workflows, optimizing infrastructure, and building scalable efficient solutions.