70 lines
2.3 KiB
Python
70 lines
2.3 KiB
Python
import subprocess
|
||
import os
|
||
|
||
def run_command(command, check=True, shell=True):
|
||
"""执行shell命令并返回结果,包含错误处理"""
|
||
try:
|
||
print(f"执行命令: {command}")
|
||
result = subprocess.run(
|
||
command,
|
||
shell=shell,
|
||
check=check,
|
||
stdout=subprocess.PIPE,
|
||
stderr=subprocess.PIPE,
|
||
text=True
|
||
)
|
||
print(f"命令输出: {result.stdout}")
|
||
return result
|
||
except subprocess.CalledProcessError as e:
|
||
print(f"命令执行失败: {e.stderr}")
|
||
raise
|
||
|
||
def main():
|
||
container_name = "user_gateway_api"
|
||
script_dir = os.path.dirname(os.path.abspath(__file__)) # 获取当前脚本所在目录
|
||
|
||
try:
|
||
# 1. 删除已存在的容器
|
||
print("===== 步骤1: 删除已存在的容器 =====")
|
||
run_command(f"sudo docker rm -f {container_name}", check=False)
|
||
|
||
# 2. 启动新容器
|
||
print("\n===== 步骤2: 启动新容器 =====")
|
||
run_command(
|
||
f"sudo docker run -itd --name {container_name} "
|
||
f"-v {script_dir}:/app -p 30001:80 golang:1.25.0-alpine3.22"
|
||
)
|
||
|
||
# 3-5. 进入容器、进入app目录并执行go mod tidy(使用sh而非bash)
|
||
print("\n===== 步骤3-5: 容器内操作 =====")
|
||
exec_commands = (
|
||
"cd /app && " # 进入app目录
|
||
"echo '当前目录内容:' && ls -la && " # 新增目录检查
|
||
"go version && " # 检查Go版本
|
||
"go mod init user_gateway && " # 执行依赖整理
|
||
"go mod tidy && " # 执行依赖整理
|
||
"exit" # 退出容器
|
||
)
|
||
|
||
# 使用sh代替bash执行命令
|
||
run_command(
|
||
f"sudo docker exec -it {container_name} sh -c '{exec_commands}'"
|
||
)
|
||
|
||
# 7. 删除容器
|
||
print("\n===== 步骤7: 删除容器 =====")
|
||
run_command(f"sudo docker rm -f {container_name}")
|
||
|
||
# 8. 删除虚悬镜像
|
||
print("\n===== 步骤8: 清理虚悬镜像 =====")
|
||
run_command("sudo docker images -f 'dangling=true' -q | xargs -r sudo docker rmi")
|
||
|
||
print("\n===== 所有操作完成 =====")
|
||
|
||
except Exception as e:
|
||
print(f"\n操作失败: {str(e)}")
|
||
exit(1)
|
||
|
||
if __name__ == "__main__":
|
||
main()
|