Automate Your Docker Build

In previous articles, we build some Docker and Podman containers by manually executing shell commands.

Table of contents

No heading

No headings in the article.

But of course, this can be automated, so here is an example of a simple bash script that does just that. It can be used to build and update your Docker build.

Steps:

  • Set variables for the application URL and the process_id.

  • Wait until the process is finished before moving to the next process.

  • If there is a running container stop that first.

  • Remove the stopped container.

  • Remove the docker images (alpine and app in this case).

  • Build a new image and tag it with 'latest'.

  • Run a new container (app) on port 8888.

  • Check exit status.

  • Open the application in your browser.

#!/bin/bash

URL=$"http://localhost:8888"
process_id=$!

docker stop app
echo "container stopped"
wait $process_id

docker rm app
wait $process_id
echo "container removed"

docker rmi alpine
wait $process_id

docker rmi app
wait $process_id
echo "images removed"

docker build -t app:latest -f Dockerfile .
echo "new image build"
wait $process_id

docker run -dt --name app -p 8888:80 forrestgreen:latest
echo "running new container now"
wait $process_id

echo "Exit status: $?"
echo "all processes finished"

[[ -x $BROWSER ]] && exec "$BROWSER" "$URL"
path=$(which xdg-open || which gnome-open) && exec "$path" "$URL"
if open -Ra "Google Chrome"; then
  echo "opening application now"
  open -a "Google Chrome" "$URL"
else
  echo "no system browser installed"
fi