今天就來小試身手,用 Ansible 部署 Nginx,在 Cloud Native 的開發中,平台(Cloud Provider)也會有 Load Balancer ,像是 AWS 的 NLB、ALB,或是早些年的 ELB。這裡的 Nginx 的作用,是在平台提供的 LB 後面,作 App Layer 的導流與 Reverse Proxy,見下圖。
我們會把每一個微服務要用到的 docker 獨立出來寫作一個 Yaml 檔,這樣的好處是,當你在堡壘機(bastion)上,要作目標環境(e.g. staging, production)作操作時,操作的彈性比較大,一個簡單的部署範例如下
$ cat roles/tasks/run_nginx.yaml
- name: File | Remove Directories
file:
path: '{{ item }}'
state: absent
owner: centos
group: centos
with_items:
- "{{ prd_dir }}/nginx/cert"
- "{{ prd_dir }}/nginx/conf"
- "{{ prd_dir }}/nginx/html"
- "{{ prd_dir }}/nginx/log"
- name: File | Create Directories
file:
path: '{{ item }}'
state: directory
owner: centos
group: centos
with_items:
- "{{ prd_dir }}/nginx/cert"
- "{{ prd_dir }}/nginx/conf"
- "{{ prd_dir }}/nginx/html"
- "{{ prd_dir }}/nginx/log"
- name: Copy | Copy Cert File to Remote
copy:
src: "{{ dev_dir }}/files/cert.d/{{ item }}"
dest: "{{ prd_dir }}/nginx/cert"
with_items:
- fullchain.pem
- privkey.pem
- ssl-dhparam.pem
- name: Copy | Copy Config File to Remote
copy:
src: "{{ dev_dir }}/files/conf.d/nginx.conf"
dest: "{{ prd_dir }}/nginx/conf"
- name: Copy | Copy Maintenance HTML to Remote
copy:
src: "{{ dev_dir }}/files/html.d/maintenance.html"
dest: "{{ prd_dir }}/nginx/html"
- name: Docker | Start nginx.mytodos
docker_container:
networks_cli_compatible: yes
name: nginx.mytodos
state: started
domainname: nginx.mytodos
image: nginx:1.14.2-alpine
networks:
- name: mynet
ipv4_address: 172.20.0.2
ports:
- '443:443' # port_on_host:port_on_docker
restart: true
volumes:
- /usr/share/zoneinfo/UTC:/etc/localtime:ro
- /sys/fs/cgroup:/sys/fs/cgroup:ro
- "{{ prd_dir }}/nginx/cert:/etc/nginx/cert.d:ro"
- "{{ prd_dir }}/nginx/conf/:/etc/nginx/conf.d:ro"
- "{{ prd_dir }}/nginx/html:/var/www/html:ro"
- "{{ prd_dir }}/nginx/log:/var/log/nginx"