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

MySQL installation and configuration method graphic tutorial (CentOS7)

1. System environment [root@localhost home]# cat ...

Detailed analysis of the difference between Ref and Reactive in Vue3.0

Table of contents Ref and Reactive Ref Reactive T...

MySQL derived table (Derived Table) simple usage example analysis

This article uses an example to describe the simp...

A quick solution to accidentally delete MySQL data (MySQL Flashback Tool)

Overview Binlog2sql is an open source MySQL Binlo...

Solution for installing opencv 3.2.0 in Ubuntu 18.04

Download opencv.zip Install the dependencies ahea...

About Docker security Docker-TLS encrypted communication issues

Table of contents 1. Security issues with Docker ...

How to find out uncommitted transaction information in MySQL

A while ago, I wrote a blog post titled "Can...

How to use webpack and rollup to package component libraries

Preface I made a loading style component before. ...

Solution to docker suddenly not being accessible from the external network

According to the methods of the masters, the caus...

What are inline elements and block elements?

1. Inline elements only occupy the width of the co...

An Incomplete Guide to JavaScript Toolchain

Table of contents Overview Static type checking C...

The difference between ENTRYPOINT and CMD in Dockerfile

In the Docker system learning tutorial, we learne...