ansible-05 在ubuntu安装Nginx

使用ansible在ubuntu安装Nginx的方法及遇到的问题

剧本如下

- name: 部署 Nginx 容器并同步配置文件
  hosts: nginx_servers
  become: true
  vars:
    host_html_dir: "/data/nginx/html"
    host_conf_dir: "/data/nginx/conf.d"
    # 本地配置文件路径(相对于 Playbook)
    local_conf_dir: "roles/nginx/files/conf.d"
  tasks:
    - name: 检查 Nginx 容器是否存在
      docker_container_info:
        name: my_nginx
      register: nginx_container

    - name: 拉取最新的 Nginx 镜像
      docker_image:
        name: nginx:latest
        source: pull
      when: not nginx_container.exists

    - name: 创建宿主机存储目录
      block:
        - name: 创建HTML目录
          file:
            path: "{{ host_html_dir }}"
            state: directory
            mode: '0755'
        
        - name: 创建配置目录
          file:
            path: "{{ host_conf_dir }}"
            state: directory
            mode: '0755'

    - name: 同步本地配置文件到目标服务器
      copy:
        src: "{{ local_conf_dir }}/"  # 同步整个 conf.d 目录
        dest: "{{ host_conf_dir }}/"
        owner: root
        group: root
        mode: '0644'       # 文件权限
        directory_mode: '0755'  # 目录权限
        # 若需覆盖已有文件,取消注释下方行
        # force: yes

    - name: 确保存在默认首页
      copy:
        dest: "{{ host_html_dir }}/index.html"
        content: |
          <html>
            <body>Hello from Nginx Container!</body>
          </html>
        mode: '0644'

    - name: 启动或重新创建 Nginx 容器
      docker_container:
        name: my_nginx
        image: nginx:latest
        state: started
        restart_policy: unless-stopped
        ports:
          - "0.0.0.0:80:80"  # 绑定到所有网络接口
        volumes:
          - "{{ host_html_dir }}:/usr/share/nginx/html:Z"
          - "{{ host_conf_dir }}:/etc/nginx/conf.d:Z"

遇到的问题

问题1

服务器docker连不上默认的镜像源

TASK [拉取最新的 Nginx 镜像] ***************************************************

fatal: [node140]: FAILED! => {"changed": false, "msg": "Error pulling image nginx:latest - 500 Server Error for http+docker://localhost/v1.48/images/create?tag=latest&fromImage=nginx: Internal Server Error (\"Get \"https://registry-1.docker.io/v2/\": net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers)\")"}

解决办法:
1、首先用curl查看是否能够连上镜像,确认不能连上
curl -v https://registry-1.docker.io/v2/
2、编辑vi /etc/docker/daemon.json,修改配置为

{
  "registry-mirrors": ["https://docker.m.daocloud.io"],
  "live-restore": true
}

3、刷新配置

systemctl daemon-reload
systemctl restart docker

4、查看配置docker info | grep -A5 'Registry Mirrors'

问题2

Nginx安装成功后,在本地浏览器访问ip:8080无法链接到。而在服务器使用curl http://ip:8080 就可以访问。此时需要查看防火墙或者某某云上的规则管控,端口啥的是否开放了,如果没开放就需要放开。然后就能正常访问了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值