Ubuntu 22.04 VPS服务器Docker API调用教程
文章分类:更新公告 /
创建时间:2025-07-31
想在Ubuntu 22.04 VPS服务器上通过编程管理Docker容器?Docker API就是关键工具。它能让你通过代码远程操作容器,实现启动、停止、监控等自动化管理。本文手把手教你在Ubuntu 22.04 VPS服务器上配置并调用Docker API,从环境准备到实际操作一步到位。
第一步:确认环境基础
首先确认VPS服务器已安装Ubuntu 22.04系统,且Docker服务正常运行。打开终端输入命令检查Docker版本:
docker --version
若提示"command not found",说明未安装。执行以下命令安装Docker(基于Ubuntu的apt包管理):
sudo apt update && sudo apt install -y docker.io
安装完成后启动服务并设置开机自启:
sudo systemctl start docker
sudo systemctl enable docker
第二步:开启Docker API网络监听
默认情况下,Docker API仅通过Unix套接字(/var/run/docker.sock)本地通信。要远程调用API,需配置网络监听端口。
用nano编辑器修改Docker服务配置文件:
sudo nano /lib/systemd/system/docker.service
找到以"ExecStart"开头的行,在末尾添加网络监听参数:
ExecStart=/usr/bin/dockerd -H tcp://0.0.0.0:2375 -H unix:///var/run/docker.sock
(注:-H参数指定监听地址,tcp://0.0.0.0:2375表示监听所有IP的2375端口,unix://保持本地套接字通信)
保存退出后,重新加载systemd配置并重启Docker:
sudo systemctl daemon-reload
sudo systemctl restart docker
第三步:实际调用Docker API
配置完成后,可通过HTTP请求操作Docker。以下是3个常用场景的实操示例:
1. 查看运行中的容器
用curl发送GET请求获取容器列表:
curl http://localhost:2375/containers/json
返回结果是JSON格式,包含容器ID、名称、状态等信息。例如:
[
{
"Id": "abc123...",
"Names": ["/my_nginx"],
"State": "running"
}
]
2. 创建并启动Nginx容器
发送POST请求创建容器(指定镜像为nginx:latest):
curl -X POST -H "Content-Type: application/json" -d '{
"Image": "nginx:latest",
"HostConfig": { "PortBindings": { "80/tcp": [{"HostPort": "8080"}] } }
}' http://localhost:2375/containers/create?name=my_nginx
创建成功后返回容器ID,接着启动容器:
curl -X POST http://localhost:2375/containers/my_nginx/start
3. 用Python脚本自动化操作
除了命令行,更推荐用Python编写自动化脚本。安装requests库后(pip install requests),编写以下脚本:
import requests
获取所有运行中容器
def get_containers():
url = "http://localhost:2375/containers/json"
try:
res = requests.get(url)
res.raise_for_status()
return res.json()
except Exception as e:
print(f"获取容器失败:{str(e)}")
return []
主程序
if __name__ == "__main__":
containers = get_containers()
if containers:
print("当前运行的容器:")
for c in containers:
print(f"名称:{c['Names'][0]} 状态:{c['State']}")
else:
print("无运行中的容器")
保存为docker_manager.py,运行命令:
python3 docker_manager.py
通过以上步骤,你已掌握在Ubuntu 22.04 VPS服务器上调用Docker API的核心方法。实际使用时需注意:直接监听0.0.0.0:2375有安全风险,生产环境建议通过防火墙限制访问源,或配置TLS认证(可通过--tls参数实现)。掌握Docker API后,你可以结合定时任务或CI/CD工具,轻松实现容器的自动化部署与监控,大幅提升运维效率。