Shell Script to Build Docker Image [2 Steps]

In this article, We are going to cover Shell Script to Build Docker Image

Introduction

If you want to create docker image and docker container using shell script this article will help you.

Prerequisites

1. Shell Script to Build Docker Image

Create a bash file named builddockerimage.sh on terminal

sudo nano builddockerimage.sh

Paste the below shell script into it

#!/bin/bash




########################################################

## Shell Script to Build Docker Image by FOSSTechNix.com   

########################################################


DATE=`date +%Y.%m.%d.%H.%M`
username=<git username>
password=<password>
DIR=/home/sivasaisagar/helloworld
FILE=/home/sivasaisagar/output
container_name=helloworld
if [ -d "$DIR" ];
then
printf '%s\n' "helloworld dir ($DIR)"
rm -rf "$DIR"
else
echo "now no helloworld a dir"
fi
echo "cloning a helloworld dir"
sudo git clone https://<username>:<password>@github.com/USivaSaiSagar/helloworld.git
result=$( sudo docker images -q helloworld )
if [[ -n "$result" ]]; then
echo "image exists"
sudo docker rmi -f helloworld
else
echo "No such image"
fi
echo "change the dir"

echo "delete output file"
cd /home/sivasaisagar/helloworld/
echo "build the docker image"
sudo docker build -t helloworld/sivasai:$DATE . >> /home/sivasaisagar/output
echo "built docker images and proceeding to delete existing container"
result=$( docker ps -q -f name=helloworld )
if [[ $? -eq 0 ]]; then
echo "Container exists"
sudo docker container rm -f helloworld
echo "Deleted the existing docker container"
else
echo "No such container"
fi
echo "Deploying the updated container"
sudo docker run -itd -p 3000:3000 --name helloworld $OUTPUT
echo "Deploying the container"

Before proceeding, note that there are two mechanical requirements to enable shell script execution.

  • The script must be “executable”.
  • The script must be “findable” for execution.
$ sudo chmod +x /home/builddockerimage.sh

OR

$ sudo chmod 0755 /home/builddockerimage.sh

2. Run the Shell Script

Now the Run the shell script using below command

bash builddockerimage.sh

Conclusion

In this article, We have covered Shell Script to Build Docker Image.

Related Articles:

Shell Script for MySQL DataBase Backup

Shell Script to Start MongoDB Service if Down [2 Steps]

Docker Tutorial for Beginners

100 Docker Basic Commands with Examples

Reference:

Docker Official Reference Page

Sivasai Sagar

I am working as DevOps Engineer and having 5 years of Experience. Likes to share knowledge.

4 thoughts on “Shell Script to Build Docker Image [2 Steps]”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share via
Copy link
Powered by Social Snap