温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何用Ansible部署Web服务

发布时间:2026-09-21 06:57:54 来源:亿速云 阅读:86 作者:小樊 栏目:系统运维

下面给你一个用 Ansible 部署 Web 服务的完整思路和示例,以 Nginx + 静态/动态站点 为例,适合入门到中等复杂度场景。


一、整体架构示例

假设环境如下:

  • 控制机:你本地或跳板机(装 Ansible)
  • 目标机:1 台或多台 Linux 服务器(CentOS / Ubuntu)
  • Web 服务:Nginx
  • 部署内容:HTML 或 后端代码(如 Flask / Node)

二、准备工作

1. 安装 Ansible(控制机)

# Ubuntu / Debian
sudo apt update
sudo apt install ansible -y

# CentOS
sudo yum install epel-release -y
sudo yum install ansible -y

验证:

ansible --version

2. 配置主机清单(inventory)

hosts.ini

[web]
192.168.1.10
192.168.1.11

[web:vars]
ansible_user=root
ansible_ssh_private_key_file=~/.ssh/id_rsa

测试连通性:

ansible web -i hosts.ini -m ping

三、编写 Playbook(核心)

示例:部署 Nginx 并发布静态网站

deploy_web.yml

---
- name: Deploy Nginx Web Service
  hosts: web
  become: yes

  tasks:
    - name: Install Nginx
      apt:
        name: nginx
        state: latest
      when: ansible_os_family == "Debian"

    - name: Install Nginx (CentOS)
      yum:
        name: nginx
        state: latest
      when: ansible_os_family == "RedHat"

    - name: Start and enable Nginx
      service:
        name: nginx
        state: started
        enabled: yes

    - name: Copy website files
      copy:
        src: ./site/
        dest: /var/www/html/
        mode: '0644'

    - name: Configure Nginx site
      template:
        src: nginx.conf.j2
        dest: /etc/nginx/sites-available/default
      notify: Restart Nginx

  handlers:
    - name: Restart Nginx
      service:
        name: nginx
        state: restarted

四、模板文件(可选但推荐)

nginx.conf.j2

server {
    listen 80;
    server_name {{ ansible_hostname }};

    root /var/www/html;
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }
}

五、目录结构建议

.
├── hosts.ini
├── deploy_web.yml
├── nginx.conf.j2
└── site/
    └── index.html

六、执行部署

ansible-playbook -i hosts.ini deploy_web.yml

访问:

http://目标服务器IP

七、常见扩展方案

✅ 部署后端服务(如 Flask)

  • systemd 模块管理服务
  • pip / git 模块拉代码
  • uwsgi / gunicorn + Nginx

✅ 多环境

[web:prod]
192.168.1.10

[web:test]
192.168.2.10

✅ 使用 Roles(推荐)

ansible-galaxy init nginx

八、调试技巧

ansible web -m setup           # 查看主机变量
ansible-playbook xxx.yml --check
ansible-playbook xxx.yml -vvv

如果你愿意,我可以:

  • ✅ 给你 Flask / Node / Java Web 的 Ansible 示例
  • ✅ 帮你写成 Ansible Role
  • ✅ 结合 Docker / Kubernetes 部署

你现在的 Web 服务是哪种?

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI