Detailed explanation of Shell script control docker container startup order

Detailed explanation of Shell script control docker container startup order

1. Problems encountered

In the process of distributed project deployment, it is often required that the application (including database) can be automatically restored after the server is restarted. Although using docker update --restart=always containerid can make the container automatically start with docker, it cannot guarantee that it will start after the database is started. If the database is not started, the application startup will fail. There is also a solution on the Internet to control the startup order through docker-compose container arrangement, which is less studied by the blogger.

2. Solution

Use Shell script to control, the idea is as follows

Detect the database port to verify whether the database is started successfully. After the database is started successfully, detect the ports of the configuration center and the service registration center to verify whether they are started successfully. After the database and the configuration center are started, start other microservice applications.

3. Port detection

The command used for port detection is

nc -w 1 host port </dev/null && echo "200"

host: the IP address of the target host

port: the port the service listens on

If the service is started, this command will return 200, otherwise it will return nothing.

4. Shell Script

Paste the code directly, the configuration center used is nacos

#!/bin/bash
#chkconfig: 2345 80 90
#description:autoStartMaintenanceService.sh
#
#premise:
#1.Docker must be able to start automatically when the computer is turned on#2.Docker can start the operation and maintenance service normally#3.This script must be run on the machine where the microservice is located#
##Configuration that needs to be modified-----Start##IP of the machine where the database is located
DATABASE_HOST=192.169.1.52
##Database listening port DATABASE_PORT=3306
##IP of the machine where the microservice is located
LOCAL_HOST=192.169.1.46
##Microservice access port Maintenance_Port=8180
##IP of the machine where NACOS is located
NACOS_HOST=192.169.1.82
##NACOS listening port NACOS_PORT=8848
##Microservice container name (NAMES column)
Maintenance_Container_Name="umc-maintenance"
##The log path generated by the script Log_Path=/home/test/log
##Configuration that needs to be modified-----End##
##Loop delay time (s) LOOP_TIME=5
at_time=""
at_date=""

getAtTime() {
 at_time="$(date +%Y-%m-%d-%H:%M:%S) --- "
 at_date=$(date +%Y-%m-%d)
}

autoStartWebService() {
 ##If the log path does not exist, create it if [ ! -d "$Log_Path" ]; then
  mkdir -p $Log_Path
 fi

 while true; do
  ##Judge whether the database is started req_message=$(nc -w 1 ${DATABASE_HOST} ${DATABASE_PORT} </dev/null && echo "200")
  if [ -n "$req_message" ]; then
   getAtTime
   echo "$at_time Database is running" >>${Log_Path}/"$at_date"_autoStartMaintenanceService.log
   waitNacosStarting
  else
   getAtTime
   echo "$at_time Database is not running and please wait for Database starting" >>${Log_Path}/"$at_date"_autoStartMaintenanceService.log
   sleep $LOOP_TIME
  fi
 done
}
##Judge whether Nacos is started waitNacosStarting() {
 req_message=$(nc -w 1 ${NACOS_HOST} ${NACOS_PORT} </dev/null && echo "200")
 if test $((req_message)) -eq 200; then
  getAtTime
  echo "$at_time Nacos is running" >>${Log_Path}/"$at_date"_autoStartMaintenanceService.log
  startMaintenanceService
  sleep $LOOP_TIME
 else
  getAtTime
  echo "$at_time Nacos is not running and please wait for nacos starting" >>${Log_Path}/"$at_date"_autoStartMaintenanceService.log
  sleep $LOOP_TIME
 fi
}

##Start the microservice startMaintenanceService() {
 req_message=$(nc -w 1 ${LOCAL_HOST} ${Maintenance_Port} </dev/null && echo "200")
 if test $((req_message)) -eq 200; then
  getAtTime
  echo "$at_time Maintenance service is running" >>${Log_Path}/"$at_date"_autoStartMaintenanceService.log
 else
  container_id=$(docker ps -a | grep $Maintenance_Container_Name | grep -v grep | awk '{print $1}')
  getAtTime
  echo "$at_time Maintenance service container id is ${container_id}" >>${Log_Path}/"$at_date"_autoStartMaintenanceService.log
  docker start ${container_id}
 fi

}

autoStartWebService

5. Shell input and output redirection

When writing this script, the blogger also became more familiar with Shell input and output redirection

Generally, each Unix/Linux command opens three files when it is run:

  • Standard input file (stdin): The file descriptor of stdin is 0, and Unix programs read data from stdin by default.
  • Standard output file (stdout): The file descriptor of stdout is 1, and Unix programs output data to stdout by default.
  • Standard error file (stderr): The file descriptor of stderr is 2, and Unix programs write error information to the stderr stream.

Command Description
command > file redirects the output to file and overwrites file
command < file redirects input to file
command >> file redirects the output to file in append mode
command 2> file will output the error to file and overwrite file
command 2>> file redirects the error to file in append mode
<< tag takes the content between the start tag and the end tag as input

If you want to merge stdout and stderr and redirect them to a file (that is, output both correct information and error information to a file), you can write:

command > file 2>&1
Or command >> file 2>&1

/dev/null file

/dev/null is a special file. Anything written to it will be discarded; if you try to read from it, you will get nothing. However, the /dev/null file is very useful. Redirecting the output of a command to it will have the effect of disabling output.

command > /dev/null 2>&1 can block stdout and stderr

refer to

Novice Tutorial - Shell

This is the end of this article about Shell script controlling the startup order of docker containers. For more relevant Shell script control docker content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Docker enables seamless calling of shell commands between container and host
  • How to monitor the running status of docker container shell script
  • How to execute Linux shell commands in Docker
  • Execute the shell or program inside the Docker container on the host
  • Use Shell scripts to batch start and stop Docker services
  • Shell script builds Docker semi-automatic compilation, packaging and release application operations

<<:  How to wrap HTML title attribute

>>:  Vue routing lazy loading details

Recommend

Vue2.x responsiveness simple explanation and examples

1. Review Vue responsive usage​ Vue responsivenes...

Docker network principles and detailed analysis of custom networks

Docker virtualizes a bridge on the host machine. ...

React gets input value and submits 2 methods examples

Method 1: Use the target event attribute of the E...

Springboot+Vue-Cropper realizes the effect of avatar cutting and uploading

Use the Vue-Cropper component to upload avatars. ...

Implementation of pushing Docker images to Docker Hub

After the image is built successfully, it can be ...

Detailed explanation of several ways to export data in Mysql

There are many purposes for exporting MySQL data,...

Super simple qps statistics method (recommended)

Statistics of QPS values ​​in the last N seconds ...

Detailed explanation of MySQL InnoDB secondary index sorting example

Sorting Problem I recently read "45 Lectures...

How to show or hide common icons on the desktop in Windows Server 2012

Windows Server 2012 and Windows Server 2008 diffe...

CSS Standard: vertical-align property

<br />Original text: http://www.mikkolee.com...

How to quickly build an FTP file service using FileZilla

In order to facilitate the storage and access of ...

How to use wangEditor in vue and how to get focus by echoing data

Rich text editors are often used when doing backg...

XHTML Basic 1.1, a mobile web markup language recommended by W3C

W3C recently released two standards, namely "...

Example code for implementing photo stacking effect with CSS

Achieve results step 1. Initial index.html To bui...

Complete steps to use samba to share folders in CentOS 7

Preface Samba is a free software that implements ...