centos开机自检及开机自启服务-Dash.shell及Systemd方法

目录

centos开机自检及开机自启服务-Dash.shell及Systemd方法

一、基本命令

二、开机登录的过程及开机自启的方法和代码

2.1、 基本过程简单概括

2.1.1、 是否云服务Docker环境镜像自动挂载

2.1.2、设备及其内核驱动挂载检测

2.1.3、挂载root

2.1.4、挂载内核态各文件系统进程并挂载内置root用户运行级别及内核跟踪

2.1.5、加载打印调度模块

2.1.6、用户登录请求及验证

2.1.7、遍历用户态进程或服务的init初始化配置

2.1.8、进入用户会话session

2.1.9、与系统启动的“用户态进程”关联的最后几个关键Target

2.1.10、按各用户态服务配置文件中定义的依赖及其顺序队列化运行服务单元

2.2、 检查用户运行时级别的服务,是否成功开机自启

2.3、附录:开机及登录过程所有服务明细

2.4、检查应用的端口监听状态(关键代码)

2.5、以.sh脚本方式,正确设定开机自启(关键代码)

2.5.1、代码分段测试

2.5.2、用依赖关系合并配置代码

2.6、以.service服务配置文件的方式,正确设定开机自启(关键代码)

2.6.1、启动mongodMyShared.service服务配置 (关键代码)

2.6.2、在终端执行脚本启动eggServer(关键代码)

2.7、mongoDB官方公布的“退出码”

附录:systemctl命令格式


        继上篇: 《Linux部署node.JS、NginX、egg、MongoDB和非js世界的后端服务之CentOS-腾讯云》,让我们来看看,在此基础上如何做“开机自启服务”。

        现如今的Linux系统,已非过去老的基于sysV的系统及其系统管理了,sysytemd为sysV的替代品,需要重新认识和学习。

        sysytemd的各项参数、执行及结果,都是通过systemctl命令行工具来完成的。journalctl命令行工具实现日志功能。

        systemctl命令行工具的主要作用:

1、options选项:Query or send control commands to the systemd manager.

    以下为各类命令:

2、Unit Commands

3、Unit File Commands

4、Machine Commands

5、Job Commands

6、Environment Commands

7、Manager Lifecycle Commands

8、System Commands

         我们学习、使用sysytemd,主要就应当从上述8大类入手实操。

一、基本命令

# 列出当前系统“内存”中,所有loaded启动、active激活、sub底级别的系统或用户服务单元

units及状态:

systemctl

# 列出当前的系统“内存”中,所有服务单元units,包括“死的”或“空的”:

systemctl --all

# 列出已安装的服务单元units:

systemctl list-unit-files

#正常loaded启动但未active激活或未能sub的服务单元units:

        systemctl --failed

或:

        systemctl --state=failed

# LOAD   = Reflects whether the unit definition was properly loaded.反映单元定义是否正确加载
# ACTIVE = The high-level unit activation state, i.e. generalization of SUB.高级别单元的激活状态,即SUB的泛化
# SUB    = The low-level unit activation state, values depend on unit type.高级别单元的激活状态,值取决于单元类型

二、开机登录的过程及开机自启的方法和代码

2.1、 基本过程简单概括

2.1.1、 是否云服务Docker环境镜像自动挂载

# 如果环境是云服务Docker,会检查镜像是否自动挂载,否则不会执行该项检测

proc-sys-fs-binfmt_misc.automount

2.1.2、设备及其内核驱动挂载检测

# 执行所有sys-devices-*开头的设备检测,比如dvd-rom、虚拟网络设备、virtio/block/vda虚拟块设备的内核驱动、serial***串口节点及设备驱动、pnp即插即用设备、以太网等:

sys-devices-*

# 执行所有系统模块加载:

sys-module-*

# 执行所有子系统的各项检测及加载:

sys-subsystem-*

2.1.3、挂载root

Root Mount 即:_.mount 

2.1.4、挂载内核态各文件系统进程并挂载内置root用户运行级别及内核跟踪

# 挂载内核支持的各类File System文件系统,比如:

# ## Huge Pages File System  :大页面文件系统(与虚拟内存有关,比如mongod不建议)

dev-hugepages.mount  

# ## POSIX Message Queue File System    :POSIX消息队列文件系统

dev-mqueue.mount  

# ## Arbitrary Executable File Formats File System  : AEF格式文件系统

proc-sys-fs-binfmt_misc.mount  

# ## FUSE Control File System  :用户空间(或称用户态)文件系统(Filesystem in Userspace),对这个文件系统进行的读写操作都会被转给用户态的程序来处理。

sys-fs-fuse-connections.mount   

# ## Kernel Configuration File System  :内核配置文件系统

 sys-kernel-config.mount  

# ## RPC Pipe File System   :远程过程调用Remote Produce Call文件系统

var-lib-nfs-rpc_pipefs.mount    

# ## Kernel Debug File System  :内核调试文件系统

# 挂载内置root用户的运行级别,比如run/user/0/*当前root用户的运行级别0(运行级别从0~6共7个):

run-user-0*

# 内核跟踪/sys/kernel/tracing  

sys-kernel-tracing.mount  


2.1.5、加载打印调度模块

# ## CUPS Scheduler :模块化开源打印系统,使用 Internet 打印协议 (Internet Printing Protocol, IPP) 作为基础来管理打印机、打印请求和打印队列。CUPS 支持网络打印机浏览和基于 PostScript 打印机描述的打印选项。CUPS还提供了跨越本地网络的公共打印接口

cups.path 

2.1.6、用户登录请求及验证

# Forward Password Requests to Plymouth Directory Watch :  将登录页面的密码请求及用户输入转发到“Plymouth目录进行监视”的命令行,Plymouth命令转储控制客户端登录

# Forward Password Requests to Wall Directory Watch  :将密码请求转发到“Wall Directory Watch目录进行监视”

2.1.7、遍历用户态进程或服务的init初始化配置

#  system and Service Manager  :进入到systemd的作用域,进行系统及其服务管理

# 即:无论是老旧的sysV还是新的systemd,均会在这个环节进入用户态程序的管理

# 老的sysV的init.d下的***.sh文件的函数代码仍然有效,只不过其中的代码必然会大量“冗余”和可能带来“环境依赖”及“主子进程间切换”的不确定性;所以,新的Linux开源标准中,普遍采纳了systemd存储库的发行代码。建议以service配置运行用户态软件的“开机自启”。

init.scope

如果未正确理解系统启动过程中的2.1.6、及2.1.7、这两个步骤及其所处的环境,“开机自启用户态”软件的服务,就是一句空话,是会出错的。

2.1.8、进入用户会话session

session *** of user root或当前登录的用户名  :开始用户会话管理

2.1.9、与系统启动的“用户态进程”关联的最后几个关键Target

  UNIT                                         LOAD      ACTIVE      SUB

  ......                                                    

  sockets.target                           loaded     actived       actived
  sshd-keygen.target                   loaded     actived       actived

  keygen.target                            loaded     actived       actived                                                
  swap.target                                loaded     actived       actived                                                
  sysinit.target                              loaded     actived       actived
  timers.target                              loaded     actived       actived

# .......................................

remote-fs.target                        loaded     actived       actived

rpc_pipefs.target                       loaded     actived       actived

rpcbind.target                            loaded     actived       actived

        上述绿色示意的几个Target,分别代表系统与用户边缘接口的内核态:远程文件系统、远程过程调用管道文件系统、远程过程调用的端口绑定。通常它们启动了,你的用户态应用进程,便具备了可启动服务的所有依赖条件。

2.1.10、按各用户态服务配置文件中定义的依赖及其顺序队列化运行服务单元

比如:

  UNIT                                         LOAD      ACTIVE      SUB

● nginx.service                            loaded     actived       actived

● mongodMyShared.service       loaded     failed          failed

● eggServerMysite.service         loaded     failed          failed
如果配置的依赖及其队列顺序不正确,可能将导致active激活异常或sub低级别异常。

2.2、 检查用户运行时级别的服务,是否成功开机自启

# 正常loaded挂载但active激活失败的所有服务单元units:

        systemctl --failed

或:

        systemctl --state=failed


        结果:

UNIT                    LOAD   ACTIVE SUB    DESCRIPTION                           
● eggServerMysite.service loaded failed failed eggServer mysite                      
● mcelog.service          loaded failed failed Machine Check Exception Logging Daemon
● mongodMyShared.service  loaded failed failed MongoDB Database Server

#正常loaded加载但active激活失败未发出active激活指令或sub指令的所有服务单元units:

        systemctl --failed --all

或:

        systemctl --state=failed --all

        结果,会发现多了一行,dnf-makecache.service :

UNIT                    LOAD   ACTIVE SUB    DESCRIPTION                           
● dnf-makecache.service   loaded failed failed dnf makecache                         
● eggServerMysite.service loaded failed failed eggServer mysite                      
● mcelog.service          loaded failed failed Machine Check Exception Logging Daemon
● mongodMyShared.service  loaded failed failed MongoDB Database Server

2.3、附录:开机及登录过程所有单元units明细

# 附录:开机及登录过程所有单元units明细:
# 

UNIT                                                                                LOAD   ACTIVE SUB       DESCRIPTION                                                                  
  proc-sys-fs-binfmt_misc.automount                                                   loaded active running   Arbitrary Executable File Formats File System Automount Point                
  sys-devices-pci0000:00-0000:00:01.1-ata1-host0-target0:0:1-0:0:1:0-block-sr0.device loaded active plugged   QEMU_DVD-ROM config-2                                                        
  sys-devices-pci0000:00-0000:00:05.0-virtio0-net-eth0.device                         loaded active plugged   Virtio network device                                                        
  sys-devices-pci0000:00-0000:00:06.0-virtio1-block-vda-vda1.device                   loaded active plugged   /sys/devices/pci0000:00/0000:00:06.0/virtio1/block/vda/vda1                  
  sys-devices-pci0000:00-0000:00:06.0-virtio1-block-vda.device                        loaded active plugged   /sys/devices/pci0000:00/0000:00:06.0/virtio1/block/vda                       
  sys-devices-platform-serial8250-tty-ttyS1.device                                    loaded active plugged   /sys/devices/platform/serial8250/tty/ttyS1                                   
  sys-devices-platform-serial8250-tty-ttyS2.device                                    loaded active plugged   /sys/devices/platform/serial8250/tty/ttyS2                                   
  sys-devices-platform-serial8250-tty-ttyS3.device                                    loaded active plugged   /sys/devices/platform/serial8250/tty/ttyS3                                   
  sys-devices-pnp0-00:04-tty-ttyS0.device                                             loaded active plugged   /sys/devices/pnp0/00:04/tty/ttyS0                                            
  sys-devices-virtual-net-virbr0.device                                               loaded active plugged   /sys/devices/virtual/net/virbr0                                              
  sys-devices-virtual-net-virbr0\x2dnic.device                                        loaded active plugged   /sys/devices/virtual/net/virbr0-nic                                          
  sys-module-configfs.device                                                          loaded active plugged   /sys/module/configfs                                                         
  sys-module-fuse.device                                                              loaded active plugged   /sys/module/fuse                                                             
  sys-subsystem-net-devices-eth0.device                                               loaded active plugged   Virtio network device                                                        
  sys-subsystem-net-devices-virbr0.device                                             loaded active plugged   /sys/subsystem/net/devices/virbr0                                            
  sys-subsystem-net-devices-virbr0\x2dnic.device                                      loaded active plugged   /sys/subsystem/net/devices/virbr0-nic                                        
  -.mount                                                                             loaded active mounted   Root Mount                                                                   
  dev-hugepages.mount                                                                 loaded active mounted   Huge Pages File System                                                       
  dev-mqueue.mount                                                                    loaded active mounted   POSIX Message Queue File System                                              
  proc-sys-fs-binfmt_misc.mount                                                       loaded active mounted   Arbitrary Executable File Formats File System                                
  run-user-0-gvfs.mount                                                               loaded active mounted   /run/user/0/gvfs                                                             
  run-user-0.mount                                                                    loaded active mounted   /run/user/0                                                                  
  sys-fs-fuse-connections.mount                                                       loaded active mounted   FUSE Control File System                                                     
  sys-kernel-config.mount                                                             loaded active mounted   Kernel Configuration File System                                             
  sys-kernel-debug-tracing.mount                                                      loaded active mounted   /sys/kernel/debug/tracing                                                    
  sys-kernel-debug.mount                                                              loaded active mounted   Kernel Debug File System                                                     
  sys-kernel-tracing.mount                                                            loaded active mounted   /sys/kernel/tracing                                                          
  var-lib-nfs-rpc_pipefs.mount                                                        loaded active mounted   RPC Pipe File System                                                         
  cups.path                                                                           loaded active running   CUPS Scheduler                                                               
  systemd-ask-password-plymouth.path                                                  loaded active waiting   Forward Password Requests to Plymouth Directory Watch                        
  systemd-ask-password-wall.path                                                      loaded active waiting   Forward Password Requests to Wall Directory Watch                            
  init.scope                                                                          loaded active running   System and Service Manager                                                   
  session-11.scope                                                                    loaded active abandoned Session 11 of user root                                                      
  session-360.scope                                                                   loaded active running   Session 360 of user root                                                     
  session-361.scope                                                                   loaded active running   Session 361 of user root                                                     
  session-362.scope                                                                   loaded active running   Session 362 of user root                                                     
  session-364.scope                                                                   loaded active running   Session 364 of user root                                                     
  session-365.scope                                                                   loaded active running   Session 365 of user root                                                     
  session-416.scope                                                                   loaded active running   Session 416 of user root                                                     
  session-417.scope                                                                   loaded active running   Session 417 of user root                                                     
  session-418.scope                                                                   loaded active running   Session 418 of user root                                                     
  session-419.scope                                                                   loaded active running   Session 419 of user root                                                     
  session-420.scope                                                                   loaded active running   Session 420 of user root                                                     
  acpid.service                                                                       loaded active running   ACPI Event Daemon                                                            
  atd.service                                                                         loaded active running   Job spooling tools                                                           
  auditd.service                                                                      loaded active running   Security Auditing Service                                                    
  avahi-daemon.service                                                                loaded active running   Avahi mDNS/DNS-SD Stack                                                      
  chronyd.service                                                                     loaded active running   NTP client/server                                                            
  cloud-config.service                                                                loaded active exited    Apply the settings specified in cloud-config                                 
  cloud-final.service                                                                 loaded active exited    Execute cloud user/final scripts                                             
  cloud-init-local.service                                                            loaded active exited    Initial cloud-init job (pre-networking)                                      
  cloud-init.service                                                                  loaded active exited    Initial cloud-init job (metadata service crawler)                            
  crond.service                                                                       loaded active running   Command Scheduler                                                            
  cups.service                                                                        loaded active running   CUPS Scheduler                                                               
  dbus.service                                                                        loaded active running   D-Bus System Message Bus                                                     
  dracut-shutdown.service                                                             loaded active exited    Restore /run/initramfs on shutdown                                           
● eggServerMysite.service                                                             loaded failed failed    eggServer mysite                                                             
  getty@tty1.service                                                                  loaded active running   Getty on tty1                                                                
  gssproxy.service                                                                    loaded active running   GSSAPI Proxy Daemon                                                          
  import-state.service                                                                loaded active exited    Import network configuration from initramfs                                  
  iscsi-shutdown.service                                                              loaded active exited    Logout off all iSCSI sessions on shutdown                                    
  kdump.service                                                                       loaded active exited    Crash recovery kernel arming                                                 
  kmod-static-nodes.service                                                           loaded active exited    Create list of required static device nodes for the current kernel           
  ksm.service                                                                         loaded active exited    Kernel Samepage Merging                                                      
  ksmtuned.service                                                                    loaded active running   Kernel Samepage Merging (KSM) Tuning Daemon                                  
  libstoragemgmt.service                                                              loaded active running   libstoragemgmt plug-in server daemon                                         
  lvm2-monitor.service                                                                loaded active exited    Monitoring of LVM2 mirrors, snapshots etc. using dmeventd or progress polling
● mcelog.service                                                                      loaded failed failed    Machine Check Exception Logging Daemon                                       
  ModemManager.service                                                                loaded active running   Modem Manager                                                                
● mongodMyShared.service                                                              loaded failed failed    MongoDB Database Server                                                      
  netcf-transaction.service                                                           loaded active exited    Rollback uncommitted netcf network config change transactions                
  NetworkManager-wait-online.service                                                  loaded active exited    Network Manager Wait Online                                                  
  NetworkManager.service                                                              loaded active running   Network Manager                                                              
  nginx.service                                                                       loaded active running   The nginx HTTP and reverse proxy server                                      
  nis-domainname.service                                                              loaded active exited    Read and set NIS domainname from /etc/sysconfig/network                      
  packagekit.service                                                                  loaded active running   PackageKit Daemon                                                            
  plymouth-quit-wait.service                                                          loaded active exited    Hold until boot process finishes up                                          
  plymouth-quit.service                                                               loaded active exited    Terminate Plymouth Boot Screen                                               
  plymouth-read-write.service                                                         loaded active exited    Tell Plymouth To Write Out Runtime Data                                      
  plymouth-start.service                                                              loaded active exited    Show Plymouth Boot Screen                                                    
  polkit.service                                                                      loaded active running   Authorization Manager                                                        
  qcloud-srv.service                                                                  loaded active exited    Qcloud Configuration Service                                                 
  rc-local.service                                                                    loaded active exited    /etc/rc.d/rc.local Compatibility                                             
  rpc-statd-notify.service                                                            loaded active exited    Notify NFS peers of a restart                                                
  rpcbind.service                                                                     loaded active running   RPC Bind                                                                     
  rsyslog.service                                                                     loaded active running   System Logging Service                                                       
  serial-getty@ttyS0.service                                                          loaded active running   Serial Getty on ttyS0                                                        
  smartd.service                                                                      loaded active running   Self Monitoring and Reporting Technology (SMART) Daemon                      
  sshd.service                                                                        loaded active running   OpenSSH server daemon                                                        
  sssd.service                                                                        loaded active running   System Security Services Daemon                                              
  systemd-fsck-root.service                                                           loaded active exited    File System Check on Root Device                                             
  systemd-journal-flush.service                                                       loaded active exited    Flush Journal to Persistent Storage                                          
  systemd-journald.service                                                            loaded active running   Journal Service                                                              
  systemd-logind.service                                                              loaded active running   Login Service                                                                
  systemd-machined.service                                                            loaded active running   Virtual Machine and Container Registration Service                           
  systemd-modules-load.service                                                        loaded active exited    Load Kernel Modules                                                          
  systemd-random-seed.service                                                         loaded active exited    Load/Save Random Seed                                                        
  systemd-remount-fs.service                                                          loaded active exited    Remount Root and Kernel File Systems                                         
  systemd-sysctl.service                                                              loaded active exited    Apply Kernel Variables                                                       
  systemd-tmpfiles-setup-dev.service                                                  loaded active exited    Create Static Device Nodes in /dev                                           
  systemd-tmpfiles-setup.service                                                      loaded active exited    Create Volatile Files and Directories                                        
  systemd-udev-trigger.service                                                        loaded active exited    udev Coldplug all Devices                                                    
  systemd-udevd.service                                                               loaded active running   udev Kernel Device Manager                                                   
  systemd-update-utmp.service                                                         loaded active exited    Update UTMP about System Boot/Shutdown                                       
  systemd-user-sessions.service                                                       loaded active exited    Permit User Sessions                                                         
  tat_agent.service                                                                   loaded active running   tat_agent                                                                    
  tuned.service                                                                       loaded active running   Dynamic System Tuning Daemon                                                 
  user-runtime-dir@0.service                                                          loaded active exited    User runtime directory /run/user/0                                           
  user@0.service                                                                      loaded active running   User Manager for UID 0                                                       
  vdo.service                                                                         loaded active exited    VDO volume services                                                          
  -.slice                                                                             loaded active active    Root Slice                                                                   
  machine.slice                                                                       loaded active active    Virtual Machine and Container Slice                                          
  system-getty.slice                                                                  loaded active active    system-getty.slice                                                           
  system-serial\x2dgetty.slice                                                        loaded active active    system-serial\x2dgetty.slice                                                 
  system-sshd\x2dkeygen.slice                                                         loaded active active    system-sshd\x2dkeygen.slice                                                  
  system.slice                                                                        loaded active active    System Slice                                                                 
  user-0.slice                                                                        loaded active active    User Slice of UID 0                                                          
  user.slice                                                                          loaded active active    User and Session Slice                                                       
  acpid.socket                                                                        loaded active running   ACPID Listen Socket                                                          
  avahi-daemon.socket                                                                 loaded active running   Avahi mDNS/DNS-SD Stack Activation Socket                                    
  cups.socket                                                                         loaded active running   CUPS Scheduler                                                               
  dbus.socket                                                                         loaded active running   D-Bus System Message Bus Socket                                              
  dm-event.socket                                                                     loaded active listening Device-mapper event daemon FIFOs                                             
  iscsid.socket                                                                       loaded active listening Open-iSCSI iscsid Socket                                                     
  iscsiuio.socket                                                                     loaded active listening Open-iSCSI iscsiuio Socket                                                   
  libvirtd-admin.socket                                                               loaded active listening Libvirt admin socket                                                         
  libvirtd-ro.socket                                                                  loaded active listening Libvirt local read-only socket                                               
  libvirtd.socket                                                                     loaded active listening Libvirt local socket                                                         
  lvm2-lvmpolld.socket                                                                loaded active listening LVM2 poll daemon socket                                                      
  rpcbind.socket                                                                      loaded active running   RPCbind Server Activation Socket                                             
  sssd-kcm.socket                                                                     loaded active listening SSSD Kerberos Cache Manager responder socket                                 
  systemd-coredump.socket                                                             loaded active listening Process Core Dump Socket                                                     
  systemd-initctl.socket                                                              loaded active listening initctl Compatibility Named Pipe                                             
  systemd-journald-dev-log.socket                                                     loaded active running   Journal Socket (/dev/log)                                                    
  systemd-journald.socket                                                             loaded active running   Journal Socket                                                               
  systemd-udevd-control.socket                                                        loaded active running   udev Control Socket                                                          
  systemd-udevd-kernel.socket                                                         loaded active running   udev Kernel Socket                                                           
  virtlockd.socket                                                                    loaded active listening Virtual machine lock manager socket                                          
  virtlogd.socket                                                                     loaded active listening Virtual machine log manager socket                                           
  basic.target                                                                        loaded active active    Basic System                                                                 
  cloud-config.target                                                                 loaded active active    Cloud-config availability                                                    
  cloud-init.target                                                                   loaded active active    Cloud-init target                                                            
  cryptsetup.target                                                                   loaded active active    Local Encrypted Volumes                                                      
  getty.target                                                                        loaded active active    Login Prompts                                                                
  local-fs-pre.target                                                                 loaded active active    Local File Systems (Pre)                                                     
  local-fs.target                                                                     loaded active active    Local File Systems                                                           
  multi-user.target                                                                   loaded active active    Multi-User System                                                            
  network-online.target                                                               loaded active active    Network is Online                                                            
  network-pre.target                                                                  loaded active active    Network (Pre)                                                                
  network.target                                                                      loaded active active    Network                                                                      
  nfs-client.target                                                                   loaded active active    NFS client services                                                          
  nss-user-lookup.target                                                              loaded active active    User and Group Name Lookups                                                  
  paths.target                                                                        loaded active active    Paths                                                                        
  remote-fs-pre.target                                                                loaded active active    Remote File Systems (Pre)                                                    
  remote-fs.target                                                                    loaded active active    Remote File Systems                                                          
  rpc_pipefs.target                                                                   loaded active active    rpc_pipefs.target                                                            
  rpcbind.target                                                                      loaded active active    RPC Port Mapper                                                              
  slices.target                                                                       loaded active active    Slices                                                                       
  sockets.target                                                                      loaded active active    Sockets                                                                      
  sshd-keygen.target                                                                  loaded active active    sshd-keygen.target                                                           
  swap.target                                                                         loaded active active    Swap                                                                         
  sysinit.target                                                                      loaded active active    System Initialization                                                        
  timers.target                                                                       loaded active active    Timers                                                                       
  dnf-makecache.timer                                                                 loaded active waiting   dnf makecache --timer                                                        
  systemd-tmpfiles-clean.timer                                                        loaded active waiting   Daily Cleanup of Temporary Directories                                       
  unbound-anchor.timer                                                                loaded active waiting   daily update of the root trust anchor for DNSSEC                             

# LOAD   = Reflects whether the unit definition was properly loaded.
# ACTIVE = The high-level unit activation state, i.e. generalization of SUB.
# SUB    = The low-level unit activation state, values depend on unit type.

# 166 loaded units listed.

在“腾讯云”的centos8.2镜像下,如何配置开机自动启动服务:

具体应用的案例见本人博文:

Linux部署node.JS、NginX、egg、MongoDB和非js世界的后端服务之CentOS-腾讯云_pulledup的博客-CSDN博客

需要特别说明的是,不同的云服务器服务商,其优化的Linux镜像的实例版本还与云服务器服务商的Docker后端服务有关,它们实现开机自启的脚本和服务的配置,大致方法雷同,但细节各异。

2.4、检查应用的端口监听状态(关键代码)

# 系统以root用户登录后,查看一下端口的侦听状态: 
#  (1)、web服务器nginx进程
netstat -ntulp | grep 8080
#  (2)、mongod进程
netstat -ntulp | grep 27017
#  (3)、egg后端服务
netstat -ntulp | grep 7001

        如果,结果tcp端口处于非监听状态,说明:应用所依赖的服务,并未正确运行,需要先行正确配置。

已经启动,您的“配置”才是正确的:

centos检查系统完整性 centos自检_Dash.shell开机自启

2.5、以.sh脚本方式,正确设定开机自启(关键代码)

2.5.1、代码分段测试

2.5.1.1、测试nginx的web服务器能否让前端网页跑起来

#  web服务器nginx进程:

netstat -ntulp | grep 8080

        若正常的话,8080端口承载的前端的前台网页,应该能跑起来:

centos检查系统完整性 centos自检_centos开机自启服务_02

2.5.1.2、测试mongod及其配置代码是否能让客户端连接成功

# 代码分段测试-测试mongod及其配置代码是否能让客户端连接成功:

sudo /usr/bin/mongod -f /usr/local/mongodb/mongodb.conf &>/dev/null

# 检测mongod的端口是否正常被侦听:

netstat -ntulp | grep 27017

        若正常的话,27017端口承载的mongoDB的数据库连接应当正常:

        比如vscode下:

centos检查系统完整性 centos自检_systemd开机自启服务_03

         比如Navicat下:

centos检查系统完整性 centos自检_centos开机自启服务_04

2.5.1.3、分段测试egg后端服务的配置代码是否能跑起来

# 分段测试egg后端服务的配置代码是否能跑起来:

cd /usr/local/eggServer/mysite-server-main && npm run initLinux && npm run start >/dev/null 2>&1 &

# 检测egg后端服务的端口是否正常被侦听:
netstat -ntulp | grep 7001

        若正常的话,前端的后台网页也会表现正常:

centos检查系统完整性 centos自检_centos开机自启服务_05

2.5.2、用依赖关系合并配置代码

# 步骤1:

# 任意编辑1个自定义脚本配置文件,比如egg.sh
vim /opt/egg.sh

# ###其中加入如下bash shell脚本脚本,启动mongod服务、进入egg服务目录并启动后端的服务脚本:
#!/bin/bash
sudo /usr/bin/mongod -f /usr/local/mongodb/mongodb.conf &>/dev/null &
cd /usr/local/eggServer/mysite-server-main && npm run initLinux && npm run start >/dev/null 2>&1 &
cd
# 步骤2:

# bash命令执行自定义的bash shell脚本文件egg.sh,并将其回显重定向输出到/etc/rc.local:
echo "/bin/bash /opt/egg.sh >/dev/null 2>&1 & " >>/etc/rc.local

# 再次确认脚本足以拥有能执行它的权限+x :

chmod +x /etc/rc.d/rc.local

# 步骤3:

# 确认uidgid的有效性(文件/usr/share/doc/setup-*/uidgid为空,即有效,否则清空它):

vim /usr/share/doc/setup-*/uidgid

# 进入egg后端服务目录,运行后端的服务脚本,并将其回显重定向输出到/etc/profile:
echo "cd /usr/local/eggServer/mysite-server-main && npm run initLinux && npm run start >/dev/null 2>&1 &" >>/etc/profile
# 需要说明的是:
# (1)、以 .service的方式进程守护,来“开机自启”三方应用进程,需要特殊的OS访问权限
# (2)、必须以root身份登录验证后(login.target完成后),三方应用进程的“开机自启”脚本才能生效;因为mongod的进程 和 egg服务node执行脚本,均需要root权限或预先配置好的授予特殊操作系统用户的足够权限

2.6、以.service服务配置文件的方式,正确设定开机自启(关键代码)

# 需要说明的是:
# (1)、以 .service的方式进程守护,来“开机自启”三方应用进程,需要特殊的OS访问权限
# (2)、必须以root身份登录验证后(login.target完成后),三方应用进程的“开机自启”脚本才能生效;因为mongod的进程 和 egg服务node执行脚本,均需要root权限或预先配置好的授予特殊操作系统用户的足够权限

2.6.1、启动mongodMyShared.service服务配置 (关键代码)

[Unit]
Description=MongoDB Database Server
Documentation=https://docs.mongodb.org/manual
After=remote-fs.target rpc_pipefs.target rpcbind.target

[Service]
# 下面这个默认选项User=mongod:指操作系统中创建的mongod账号,默认没有设置的,改为root
# #############
User=root
# #############
Group=root
#
# Type=dbus
# BusName=com.mysiteBlog.mongodMyShared
EnvironmentFile=-/usr/bin/mongod
PermissionsStartOnly=true
TimeoutStopSec=35
# 启动前预执行,将:/usr/bin/mongodb目录的宿主改为操作系统用户root:
ExecStartPre=/usr/bin/chown root:root /usr/bin/mongod
ExecStartPre=/usr/bin/chown root:root /usr/local/mongodb/mongod.log
ExecStartPre=/usr/bin/chown root:root /usr/local/mongodb/data/db
ExecStartPre=/usr/bin/chown root:root /tmp/mongodb-27017.sock
# :这个临时锁定.sock是首次成功启动mongod时产生的,之后它需要权限来访问;但若其它原因它被释放了,应当屏蔽ExecStartPre,否则会抛“文件或文件夹不存在”的异常。
# ###注意,不可将 ExecStartPre= 用于 需要长时间执行的进程。 因为所有由 ExecStartPre= 派生的子进程 都会在启动 ExecStart= 服务进程之前被杀死。
# 启动前预执行,将:/usr/bin/mongodb目录的###访问权限###至少改为755:
ExecStartPre=/usr/bin/chmod -R 777 /usr/bin/mongod
ExecStartPre=/usr/bin/chmod -R 777 /usr/local/mongodb/
ExecStart=/usr/bin/mongod -f /usr/local/mongodb/mongodb.conf
Type=forking
# file size:
LimitFSIZE=infinity
# cpu time:
LimitCPU=infinity
# virtual memory size:
LimitAS=infinity
# open files:
LimitNOFILE=64000
# processes/threads:
LimitNPROC=64000
# locked memory:
LimitMEMLOCK=infinity
# total threads (user+kernel):
TasksMax=infinity
TasksAccounting=false
# Recommended limits for for mongod as specified in:
# http://docs.mongodb.org/manual/reference/ulimit/#recommended-settings
# 中断后自动重启:
Restart=on-abort
# 5秒后重启:
RestartSec=5s

[Install]
WantedBy=multi-user.target
# :安装服务的文件系统预期的用户界面模式(multi-user.target多用户shell界面目标;graphical.target“图形”界面目标)

2.6.2、在终端执行脚本启动eggServer(关键代码)

# 本案,由于egg-Server内部调用连接了mongoDB服务,所以两者之间存在“相互依赖”的“启动”关系:
#     服务中需要配置很复杂的“主进程”、这两个“子进程”相互之间的“上下文切换”,才能完全“开机自启”,
#     我就不再赘述了,又兴趣的,自己去研究:
cd /usr/local/eggServer/mysite-server-main && npm run initLinux && npm run start

2.7、mongoDB官方公布的“退出码”

Exit Codes and Statuses — MongoDB Manual

附录:systemctl命令格式

systemctl命令格式:
systemctl [OPTIONS...] {COMMAND} ...

Query or send control commands to the systemd manager.

  -h --help           Show this help
     --version        Show package version
     --system         Connect to system manager
     --user           Connect to user service manager
  -H --host=[USER@]HOST
                      Operate on remote host
  -M --machine=CONTAINER
                      Operate on local container
  -t --type=TYPE      List units of a particular type
     --state=STATE    List units with particular LOAD or SUB or ACTIVE state
  -p --property=NAME  Show only properties by this name
  -a --all            Show all properties/all units currently in memory,
                      including dead/empty ones. To list all units installed on
                      the system, use the 'list-unit-files' command instead.
     --failed         Same as --state=failed
  -l --full           Don't ellipsize unit names on output
  -r --recursive      Show unit list of host and local containers
     --reverse        Show reverse dependencies with 'list-dependencies'
     --job-mode=MODE  Specify how to deal with already queued jobs, when
                      queueing a new job
  -T --show-transaction
                      When enqueuing a unit job, show full transaction
     --show-types     When showing sockets, explicitly show their type
     --value          When showing properties, only print the value
     --check-inhibitors=MODE
                      Specify if checking inhibitors before shutting down,
                      sleeping or hibernating
  -i                  Shortcut for --check-inhibitors=no
     --kill-who=WHO   Who to send signal to
  -s --signal=SIGNAL  Which signal to send
     --now            Start or stop unit in addition to enabling or disabling it
     --dry-run        Only print what would be done
  -q --quiet          Suppress output
     --wait           For (re)start, wait until service stopped again
     --no-block       Do not wait until operation finished
     --no-wall        Don't send wall message before halt/power-off/reboot
     --no-reload      Don't reload daemon after en-/dis-abling unit files
     --no-legend      Do not print a legend (column headers and hints)
     --no-pager       Do not pipe output into a pager
     --no-ask-password
                      Do not ask for system passwords
     --global         Enable/disable/mask unit files globally
     --runtime        Enable/disable/mask unit files temporarily until next
                      reboot
  -f --force          When enabling unit files, override existing symlinks
                      When shutting down, execute action immediately
     --preset-mode=   Apply only enable, only disable, or all presets
     --root=PATH      Enable/disable/mask unit files in the specified root
                      directory
  -n --lines=INTEGER  Number of journal entries to show
  -o --output=STRING  Change journal output mode (short, short-precise,
                             short-iso, short-iso-precise, short-full,
                             short-monotonic, short-unix,
                             verbose, export, json, json-pretty, json-sse, cat)
     --firmware-setup Tell the firmware to show the setup menu on next boot
     --plain          Print unit dependencies as a list instead of a tree

Unit Commands:
  list-units [PATTERN...]             List units currently in memory
  list-sockets [PATTERN...]           List socket units currently in memory,
                                      ordered by address
  list-timers [PATTERN...]            List timer units currently in memory,
                                      ordered by next elapse
  start UNIT...                       Start (activate) one or more units
  stop UNIT...                        Stop (deactivate) one or more units
  reload UNIT...                      Reload one or more units
  restart UNIT...                     Start or restart one or more units
  try-restart UNIT...                 Restart one or more units if active
  reload-or-restart UNIT...           Reload one or more units if possible,
                                      otherwise start or restart
  try-reload-or-restart UNIT...       If active, reload one or more units,
                                      if supported, otherwise restart
  isolate UNIT                        Start one unit and stop all others
  kill UNIT...                        Send signal to processes of a unit
  freeze PATTERN...                   Freeze execution of unit processes
  thaw PATTERN...                     Resume execution of a frozen unit
  is-active PATTERN...                Check whether units are active
  is-failed PATTERN...                Check whether units are failed
  status [PATTERN...|PID...]          Show runtime status of one or more units
  show [PATTERN...|JOB...]            Show properties of one or more
                                      units/jobs or the manager
  cat PATTERN...                      Show files and drop-ins of specified units
  set-property UNIT PROPERTY=VALUE... Sets one or more properties of a unit
  help PATTERN...|PID...              Show manual for one or more units
  reset-failed [PATTERN...]           Reset failed state for all, one, or more
                                      units
  list-dependencies [UNIT]            Recursively show units which are required
                                      or wanted by this unit or by which this
                                      unit is required or wanted

Unit File Commands:
  list-unit-files [PATTERN...]        List installed unit files
  enable [UNIT...|PATH...]            Enable one or more unit files
  disable UNIT...                     Disable one or more unit files
  reenable UNIT...                    Reenable one or more unit files
  preset UNIT...                      Enable/disable one or more unit files
                                      based on preset configuration
  preset-all                          Enable/disable all unit files based on
                                      preset configuration
  is-enabled UNIT...                  Check whether unit files are enabled
  mask UNIT...                        Mask one or more units
  unmask UNIT...                      Unmask one or more units
  link PATH...                        Link one or more units files into
                                      the search path
  revert UNIT...                      Revert one or more unit files to vendor
                                      version
  add-wants TARGET UNIT...            Add 'Wants' dependency for the target
                                      on specified one or more units
  add-requires TARGET UNIT...         Add 'Requires' dependency for the target
                                      on specified one or more units
  edit UNIT...                        Edit one or more unit files
  get-default                         Get the name of the default target
  set-default TARGET                  Set the default target

Machine Commands:
  list-machines [PATTERN...]          List local containers and host

Job Commands:
  list-jobs [PATTERN...]              List jobs
  cancel [JOB...]                     Cancel all, one, or more jobs

Environment Commands:
  show-environment                    Dump environment
  set-environment VARIABLE=VALUE...   Set one or more environment variables
  unset-environment VARIABLE...       Unset one or more environment variables
  import-environment [VARIABLE...]    Import all or some environment variables

Manager Lifecycle Commands:
  daemon-reload                       Reload systemd manager configuration
  daemon-reexec                       Reexecute systemd manager

System Commands:
  is-system-running                   Check whether system is fully running
  default                             Enter system default mode
  rescue                              Enter system rescue mode
  emergency                           Enter system emergency mode
  halt                                Shut down and halt the system
  poweroff                            Shut down and power-off the system
  reboot [ARG]                        Shut down and reboot the system
  kexec                               Shut down and reboot the system with kexec
  exit [EXIT_CODE]                    Request user instance or container exit
  switch-root ROOT [INIT]             Change to a different root file system
  suspend                             Suspend the system
  hibernate                           Hibernate the system
  hybrid-sleep                        Hibernate and suspend the system
  suspend-then-hibernate              Suspend the system, wake after a period of
                                      time and put it into hibernate