一、创建容器
假设我们已经创建好了一个容器,如下图所示,名字为centos7
二、创建服务
为了让容器能够开机自动运行,需要以服务的形式存在。
在/etc/systemd/system/目录,为centos7容器创建一个systemd单元配置文件:
sudo vim /etc/systemd/system/centos7-container.service
文件内容如下:
[Unit]
Description=centos7 container
After=firewalld.service ufw.service
[Service]
Restart=always
ExecStart=/usr/bin/podman start -a centos7
ExecStop=/usr/bin/podman stop centos7
[Install]
WantedBy=multi-user.target
需要注意的是ExecStart以及ExecStop命令中的容器名字一定要与要实际的容器名字完全一致
如果容器中有端口需要让外部访问,比如容器中的SSHD服务,需要按照配置与管理Ubuntu 21.10一文中所述,修改podman网络模式,这样即使开启了防火墙也不会被防火墙屏蔽,同时要求容器服务在防火墙服务之后启动,否则不能访问容器中的端口。
如果是CentOS系统,防火墙服务默认是firewalld,ubuntu系统默认是ufw,笔者是在ubuntu中为了方便使用cockpit管理,同时安装了firewalld服务,所以需要在firewalld以及ufw服务之后。
还有一种更加方便的方式,直接使用podman来生成,我们使用podman generate --help查看用法,可以看到可以生成两种文件:一种是生成Kubernetes的YAML文件,另一种就是生成systemd的单元文件。
witton@witton:~$ podman generate --help
Generate structured data based on containers, pods or volumes.
Description:
Generate structured data (e.g., Kubernetes YAML or systemd units) based on containers, pods or volumes.
Usage:
podman generate [command]
Available Commands:
kube Generate Kubernetes YAML from containers, pods or volumes.
systemd Generate systemd units.
生成systemd的单元文件,正是我们想要的。再输入podman generate systemd --help查看用法:
witton@witton:~$ podman generate systemd --help
Generate systemd units.
Description:
Generate systemd units for a pod or container.
The generated units can later be controlled via systemctl(1).
Usage: