我们常常遇到在已有镜像上开机就运行客制化脚本的需求,如果不想重新构建镜像,可以考虑本方法,利用系统的rc-local.service实现对rc.local的调用,进而启动rc.local中的客制化脚本。
以下以centos7为例:
1 拉取镜像
root@arm:~# docker pull centos:centos7
centos7: Pulling from library/centos
Digest: sha256:be65f488b7764ad3638f236b7b515b3678369a5124c47b8d32916d6487418ea4
Status: Downloaded newer image for centos:centos7
docker.io/library/centos:centos7
2 创建容器
root@arm:~# docker run -itd --name centos7 --restart always --privileged centos:centos7 /usr/sbin/init
02d4ef44a7a7d4740c6aadc6207d8fb43ee2c16d66d3e9240f48538a39dc4a33
3 进入容器
root@arm:~# docker exec -it baota1 /bin/bash
[root@02d4ef44a7a7 /]#
4 确认运行等级,N 3表示文本多用户模式
[root@02d4ef44a7a7 /]# runlevel
N 3
5 修改/lib/systemd/system/rc-local.service,增加服务安装信息
原文件如下:
[Unit]
Description=/etc/rc.d/rc.local Compatibility
ConditionFileIsExecutable=/etc/rc.d/rc.local
After=network.target
[Service]
Type=forking
ExecStart=/etc/rc.d/rc.local start
TimeoutSec=0
RemainAfterExit=yes
在最后添加两行
[Unit]
Description=/etc/rc.d/rc.local Compatibility
ConditionFileIsExecutable=/etc/rc.d/rc.local
After=network.target
[Service]
Type=forking
ExecStart=/etc/rc.d/rc.local start
TimeoutSec=0
RemainAfterExit=yes
[Install]
WantedBy=multi-user.target
6 增加rc.local执行权限
[root@02d4ef44a7a7 ~]# chmod +x /etc/rc.d/rc.local
7 设置rc-local.service开机启动
[root@02d4ef44a7a7 ~]# systemctl enable rc-local
Created symlink from /etc/systemd/system/multi-user.target.wants/rc-local.service to /usr/lib/systemd/system/rc-local.service.
8 再次确认rc-locall.service服务状态
[root@02d4ef44a7a7 ~]# systemctl status rc-local
● rc-local.service - /etc/rc.d/rc.local Compatibility
Loaded: loaded (/usr/lib/systemd/system/rc-local.service; enabled; vendor preset: disabled)
Active: active (exited) since Tue 2024-03-19 14:07:54 UTC; 10min ago
Mar 19 14:07:53 02d4ef44a7a7 systemd[1]: Starting /etc/rc.d/rc.local Compati....
Mar 19 14:07:54 02d4ef44a7a7 systemd[1]: Started /etc/rc.d/rc.local Compatib....
Hint: Some lines were ellipsized, use -l to show in full.
好了,现在可以在/etc/rc.d/rc.local添加你的脚本了。