Ansible 在多台服务器上部署 Docker 容器

使用 Ansible 在多台服务器上部署 Docker 容器

在这篇博客中,我们将讨论如何使用 Ansible 在多台服务器上部署 Docker 容器。我们将以部署 lobe-chat 容器为例,并介绍如何根据不同的服务器配置特定端口。

需求分析

我有三台服务器,分别对应不同的端口,我需要在这些服务器上定期更新 lobe-chat Docker 容器:

  • 服务器 192.0.2.1 上的端口 8080
  • 服务器 192.0.2.2 上的端口 8081
  • 服务器 192.0.2.3 上的端口 8082

环境准备

首先,确保已经安装了 Ansible 和 Docker。可以通过以下命令安装:

1
2
3
4
$ sudo apt update
$ sudo apt install software-properties-common
$ sudo apt-add-repository --yes --update ppa:ansible/ansible
$ sudo apt install ansible

确保所有目标服务器都可以通过 SSH 无密码访问。可以通过生成 SSH 密钥并将公钥添加到目标服务器的 ~/.ssh/authorized_keys 文件中来实现。

配置 Ansible Inventory

/etc/ansible/hosts 文件中添加目标服务器信息:

1
2
3
4
[chatservers]
192.0.2.1
192.0.2.2
192.0.2.3

编写 Ansible Playbook

创建一个新的 Ansible Playbook 文件,例如 update_lobe_chat.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
---
- name: Manage lobe-chat Docker container on multiple servers
hosts: chatservers
become: yes

vars:
docker_image: lobehub/lobe-chat
container_name: lobe-chat
host_ports:
- { host: "192.0.2.1", port: 8080 }
- { host: "192.0.2.2", port: 8081 }
- { host: "192.0.2.3", port: 8082 }

tasks:
- name: Set host-specific port
set_fact:
host_port: "{{ item.port }}"
with_items: "{{ host_ports }}"
when: item.host == inventory_hostname

- name: Stop lobe-chat container if it is running
docker_container:
name: "{{ container_name }}"
state: stopped
ignore_errors: yes

- name: Remove lobe-chat container if it exists
docker_container:
name: "{{ container_name }}"
state: absent
ignore_errors: yes

- name: Pull the latest lobe-chat image
docker_image:
name: "{{ docker_image }}"
source: pull

- name: Run lobe-chat container
docker_container:
name: "{{ container_name }}"
image: "{{ docker_image }}"
state: started
restart_policy: always
ports:
- "{{ host_port }}:3210"
env:
OPENAI_API_KEY: "your_openai_api_key"
GOOGLE_API_KEY: "your_google_api_key"
DEEPSEEK_API_KEY: "your_deepseek_api_key"
GROQ_API_KEY: "your_groq_api_key"
ZEROONE_API_KEY: "your_zeroone_api_key"
ACCESS_CODE: "your_access_code"
when: host_port is defined

Playbook 详解

  1. 主机组和权限

    • hosts: chatservers 表示在 chatservers 组内的所有主机上运行任务。
    • become: yes 让 Ansible 使用 sudo 权限。
  2. 变量定义

    • docker_imagecontainer_name 定义了 Docker 镜像名称和容器名称。
    • host_ports 定义了每台主机对应的端口。
  3. 任务

    • 设置主机特定端口:通过 with_items 循环和 when 条件,根据主机名设置特定端口。
    • 停止运行中的 lobe-chat 容器:如果容器正在运行则停止它。
    • 移除现有的 lobe-chat 容器:如果容器存在则移除它。
    • 拉取最新的 lobehub/lobe-chat 镜像:从 Docker Hub 拉取最新的镜像。
    • 运行 lobe-chat 容器:运行容器,并根据特定主机的端口进行映射,同时设置环境变量。

执行 Playbook

运行以下命令来执行 playbook:

1
ansible-playbook update_lobe_chat.yml

这个命令会在 chatservers 组内的三台服务器(192.0.2.1、192.0.2.2 和 192.0.2.3)上执行任务,部署并运行 lobe-chat Docker 容器,端口分别映射为8080、8081和8082。

通过使用 Ansible可以轻松地在多台服务器上部署和管理 Docker 容器。使用变量和条件,可以根据不同的服务器配置特定的设置,使得部署更加灵活和高效。


Ansible 在多台服务器上部署 Docker 容器
http://example.com/2024/07/19/Ansible-在多台服务器上部署-Docker-容器/
作者
Sanli Ma
发布于
2024年7月19日
许可协议