一、 图
二、docker-compose
1 定义 Dockerfile
先定义一个 Dockerfile,我们可以从这个 Dockerfile 中构建一个自定义的镜像,从而获取到一个我们自定义的容器。
FROM centos:7
RUN yum install -y \
vim bash-com* openssh-clients openssh-server iproute cronie;\
yum group install -y "Development Tools";yum clean all;\
localedef -c -f UTF-8 -i zh_CN zh_CN.UTF-8 && \
ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime ENV LANG=zh_CN.UTF-8
在上面的 Dockerfile 中,安装的基本的软件,和 sshd、crond 服务。
会支持 ssh 远程连接、计划任务、ip 命令 ,ss 命令, 还有开发工具。
2 定义 docker-compose
version: '3.8'
services:
slb:
build: .
image: centos7-sshd
privileged: true
command: /usr/sbin/init
hostname: slb
networks:
xiuyun_net:
tomcat1:
image: centos7-sshd
privileged: true
hostname: tomcat1.sharkyun.com
command: /usr/sbin/init
networks:
xiuyun_net:
tomcat2:
image: centos7-sshd
hostname: tomcat2.sharkyun.com
privileged: true
command: /usr/sbin/init
networks:
xiuyun_net:
mysql-master:
image: centos7-sshd
hostname: mysql-master.sharkyun.com
privileged: true
command: /usr/sbin/init
networks:
xiuyun_net:
mysql-slave:
image: centos7-sshd
hostname: mysql-slave.sharkyun.com
privileged: true
command: /usr/sbin/init
networks:
xiuyun_net:
ansible:
image: centos7-sshd
hostname: ansible.sharkyun.com
privileged: true
command: /usr/sbin/init
networks:
xiuyun_net:
networks:
xiuyun_net:
3 启动
1 Ansible 阶段
1.1 安装 阿里云的 epel 源
在 ansible 主机上执行
curl -o /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
1.2 安装 ansible
yum install ansible -y
1.3 设置不检查其他主机的公钥
在 ansible 主机上修改 文件 /etc/ansible/ansible.cfg 中如下选项
[defaults]
host_key_checking = False
继续在 ansible 主机上执行如下命令,创造自己的密钥对
ssh-keygen -N '' -f ~/.ssh/id_rsa
1.4 建立 hosts 资产清单文件
在 ansible 主机上创建文件 hosts.ini ,并写入如下内容
[nginx]
slb
[tomcat]
tomcat1
tomcat2
[mysql]
mysql-master
mysql-slave
1.5 给需要管理的机器设置 root 密码
由于这里是使用容器作为虚拟机的,所以默认情况下,root 用户没有密码,需要我们手动设置。
在宿主机上执行如下命令设置密码
docker-compose exec 服务名称 bash -c 'echo 密码 | passwd root --stdin'
docker-compose exec slb bash -c 'echo upsa | passwd root --stdin'
docker-compose exec tomcat1 bash -c 'echo upsa | passwd root --stdin'
docker-compose exec tomcat2 bash -c 'echo upsa | passwd root --stdin'
docker-compose exec mysql-master bash -c 'echo upsa | passwd root --stdin'
docker-compose exec mysql-slave bash -c 'echo upsa | passwd root --stdin'
1.6 传输公钥
以下操作在 ansible 主机上操作`以下操作在 ansible 主机上操作
send-pubkey.yml`
---
- hosts: all
gather_facts: no
remote_user: root
vars:
ansible_ssh_pass: upsa
tasks:
- name: Set authorized key taken from file
authorized_key:
user: root
state: present
key: "{{ lookup('file', '/root/.ssh/id_rsa.pub') }}"
...