ERROR 2006 (HY000) at line 115: MySQL server has gone away

 

gcp  CloudSQL 이용시 ERROR 2006 (HY000) at line 115: MySQL server has gone away 해결 방법

데이터베이스 플래그 max_allowed_packet  를 추가  합니다.

 

1.증상

[root@test-instance ~]# mysql -h db01 -uroot -p test_db < test-db.sql 
Enter password: ERROR 2006 (HY000) at line 115: MySQL server has gone away 
[root@test-instance ~]#

 

 

2. 해결방법

저장소 -> SQL -> 수정 -> 인스턴스 수정 -> 데이터베이스 플래그로 이동합니다.

max_allowed_packet 1073741824 패킷값을 추가

참고페이지: https://cloud.google.com/sql/docs/mysql/flags

 

 

3. 설정후 mysql 복구

[root@test-instance ~]# mysql -h db01 -uroot -p test_db < test-db.sql 
Enter password: 
[root@test-instance ~]#

 

 

 

 

Nginx proxy https

 

Nginx Self-sign https : http://blog.crois.net/2019/09/23/centos7-nginx-self-signed-https/ 설정하였던 VM 을

이용하여 nginx proxy 를 테스트 합니다. 상단 nginx-proxy 에만 인증서가 있으면 되며 백단 서버 두대의 경우

별도의 인증서 및 설정이 필요 하지 않습니다.

nginx 설치및 php 설치의 경우 이전 포스트를 참고해 주세요.

Nginx-Proxy 서버에서 ssl 설정을 하고 Nginx-www1 / Nginx-www2 에서는 80 port 설정만 진행 합니다.

1.Nginx-proxy 설정

[root@test ~]# vi /etc/nginx/sites-enabled/test_com.conf
server {
    listen       80;
    server_name  www.test.com test.com;
    root   /var/www/html/test.com/public_html;
    index  index.php index.html index.htm;
    location / {
        return 301 https://test.com$request_uri;
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
    }
}

server {
    listen       443 http2 ssl;
    server_name  www.test.com test.com;
    root   /var/www/html/test.com/public_html;
    index  index.php index.html index.htm;

    access_log /var/www/html/test.com/logs/access.log;
    error_log  /var/www/html/test.com/logs/error.log warn;


    ssl_certificate /etc/ssl/certs/nginx-selfsign.crt;
    ssl_certificate_key /etc/ssl/private/nginx-selfsign.key;
    ssl_dhparam /etc/ssl/certs/dhparam.pem;
    ssl_session_timeout 10m;
    ssl_session_cache shared:SSL:10m;
    ssl_session_tickets off;
    ssl_protocols TLSv1.2;
    ssl_ecdh_curve secp384r1;
    #ssl_ciphers  ECDH+AESGCM:!AES128:!RSA+AES:!aNULL:!MD5:!DSS:!DHE:!kEDH:HIGH:!eNULL:!EXPORT:!DES:!RC4:!PSK:!AECDH:!LOW:!SRP:!ADH:!RSA:TLS13-CHACHA20-POLY1305-SHA256:TLS13-AES-256-GCM-SHA384:!COMPLEMENTOFDEFAULT;
    ssl_ciphers AES256+EECDH:AES256+EDH:!aNULL;
    ssl_prefer_server_ciphers on;
    add_header Strict-Transport-Security "max-age=31536000; includeSubdomains";
#    add_header X-Frame-Options DENY;
    add_header X-Content-Type-Options nosniff;

    # OCSP Stapling ---
    # fetch OCSP records from URL in ssl_certificate and cache them
    ssl_stapling on;
    ssl_stapling_verify on;


    fastcgi_buffering               on;
    fastcgi_buffer_size             16k;
    fastcgi_buffers                 16 16k;

    # time-out settings
    fastcgi_connect_timeout         600s;
    fastcgi_send_timeout            600s;
    fastcgi_read_timeout            600s;

    # php performance settings
    sendfile                        on;
    tcp_nopush                      off;
    keepalive_requests              0;


    location / {
        rewrite ^/(/.*)$ $1 break;
        proxy_pass http://test.com;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_redirect off;
        try_files $uri $uri/ /index.php?$query_string;
    }
}
upstream test.com {
    server 10.10.10.93:80;
    server 10.10.10.94:80;
}
[root@test ~]# systemctl restart nginx

 

 

2. server 설정

[root@www1 ~]# vi /etc/nginx/sites-enabled/test_com.conf
server {
    listen       80;
    server_name  www.test.com test.com;
    root   /var/www/html/test.com/public_html;
    index  index.php index.html index.htm;
    location / {
        try_files $uri $uri/ /index.php?$query_string;
        autoindex on;
    }

    access_log  /var/www/html/test.com/logs/access.log;
    error_log  /var/www/html/test.com/logs/error.log warn;

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
    }

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

[root@www1 ~]# systemctl restart nginx ; systemctl restart php-fpm

 

 

3. web-site 확인

 

4. server log 확인

tail -f access.log 를 확인 합니다.

Nginx Self-signed https

 

nginx https 설정을 테스트 합니다.

nginx web-server 와 php71 까지 설치후 Test 도메인으로 접속을 테스트 합니다.

 

 

1. Nginx 설치

[root@test ~]# vi /etc/yum.repos.d/nginx.repo
[nginx]
name=nginx
baseurl=http://nginx.org/packages/centos/7/$basearch/
gpgcheck=0
enabled=1
[root@test ~]# yum clean all

[root@test ~]# yum install -y nginx
[root@test ~]# systemctl enable nginx ; systemctl start nginx

 

 

2. php71 설치

[root@test ~]# yum install -y epel-release yum-utils
[root@test ~]# rpm -Uvh http://ftp.riken.jp/Linux/remi/enterprise/remi-release-7.rpm
[root@test ~]# yum-config-manager --enable remi-php71
[root@test ~]# yum -y install php php-mysql php-fpm php-opcache php-gd php-ldap php-odbc php-pear php-xml php-xmlrpc php-mbstring php-soap curl curl-devel
[root@test ~]# vi /etc/php.ini
date.timezone = Asia/Seoul
[root@test ~]# vi /etc/php-fpm.d/www.conf

user = nginx
group = nginx

listen.owner = nginx
listen.group = nginx
listen.mode = 0660

[root@test ~]# systemctl restart php-fpm
[root@test ~]# systemctl enable php-fpm

 

 

3. Nginx 설정

[root@test ~]# mkdir /etc/nginx/sites-enabled
[root@test ~]# vi /etc/nginx/nginx.conf
user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*.conf;
}

[root@test ~]# vi /etc/nginx/conf.d/default.conf
server {
    listen       80 default_server;
    server_name  localhost;

    charset UTF-8;

        root   /usr/share/nginx/html;
        index  index.php index.html index.htm;
    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        #fastcgi_pass unix:/run/php-fpm/php-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

}

[root@test ~]# mkdir -p /var/www/html/test.com/{public_html,logs}
[root@test ~]# vi /etc/nginx/sites-enabled/test_com.conf
server {
    listen       80;
    server_name  www.test.com test.com;
    root   /var/www/html/test.com/public_html;
    index  index.php index.html index.htm;
    location / {
        try_files $uri $uri/ /index.php?$query_string;
        autoindex on;
    }

    access_log  /var/www/html/test.com/logs/access.log;
    error_log  /var/www/html/test.com/logs/error.log warn;

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
    }

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}



[root@test ~]# chown -R nginx:nginx /var/www/html/test.com/
[root@test ~]# systemctl restart nginx

 

 

4. SSL Certificate 생성

[root@test ~]# mkdir /etc/ssl/private
[root@test ~]# chmod 700 /etc/ssl/private
[root@test ~]# openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/ssl/private/nginx-selfsign.key -out /etc/ssl/certs/nginx-selfsign.crt
Generating a 2048 bit RSA private key
.....................................................................+++
.........................................................................................................................+++
writing new private key to '/etc/ssl/private/nginx-selfsig.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:KR
State or Province Name (full name) []:Seoul
Locality Name (eg, city) [Default City]:GangNam Gu
Organization Name (eg, company) [Default Company Ltd]:test.com
Organizational Unit Name (eg, section) []:
Common Name (eg, your name or your server's hostname) []:test.com
Email Address []:admin@test.com
[root@test ~]#
[root@test ~]# openssl dhparam -out /etc/ssl/certs/dhparam.pem 2048
Generating DH parameters, 2048 bit long safe prime, generator 2
This is going to take a long time
.................................................................
~중략
[root@test ~]#

 

 

5. Nginx 설정 변경

[root@test ~]# vi /etc/nginx/sites-enabled/test_com.conf

server {
    listen       80;
    server_name  www.test.com test.com;
    root   /var/www/html/test.com/public_html;
    index  index.php index.html index.htm;
    location / {
        return 301 https://test.com$request_uri;
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
    }
}

server {
    listen       443 http2 ssl;
    server_name  www.test.com test.com;
    root   /var/www/html/test.com/public_html;
    index  index.php index.html index.htm;

    access_log /var/www/html/test.com/logs/access.log;
    error_log  /var/www/html/test.com/logs/error.log warn;


    ssl_certificate /etc/ssl/certs/nginx-selfsign.crt;
    ssl_certificate_key /etc/ssl/private/nginx-selfsign.key;
    ssl_dhparam /etc/ssl/certs/dhparam.pem;
    ssl_session_timeout 10m;
    ssl_session_cache shared:SSL:10m;
    ssl_session_tickets off;
    ssl_protocols TLSv1.2;
    ssl_ecdh_curve secp384r1;
    #ssl_ciphers  ECDH+AESGCM:!AES128:!RSA+AES:!aNULL:!MD5:!DSS:!DHE:!kEDH:HIGH:!eNULL:!EXPORT:!DES:!RC4:!PSK:!AECDH:!LOW:!SRP:!ADH:!RSA:TLS13-CHACHA20-POLY1305-SHA256:TLS13-AES-256-GCM-SHA384:!COMPLEMENTOFDEFAULT;
    ssl_ciphers AES256+EECDH:AES256+EDH:!aNULL;
    ssl_prefer_server_ciphers on;
    add_header Strict-Transport-Security "max-age=31536000; includeSubdomains";
#    add_header X-Frame-Options DENY;
    add_header X-Content-Type-Options nosniff;

    # OCSP Stapling ---
    # fetch OCSP records from URL in ssl_certificate and cache them
    ssl_stapling on;
    ssl_stapling_verify on;


    fastcgi_buffering               on;
    fastcgi_buffer_size             16k;
    fastcgi_buffers                 16 16k;

    # time-out settings
    fastcgi_connect_timeout         600s;
    fastcgi_send_timeout            600s;
    fastcgi_read_timeout            600s;

    # php performance settings
    sendfile                        on;
    tcp_nopush                      off;
    keepalive_requests              0;


    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }
    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_read_timeout 600;
        include fastcgi_params;
    }
}
[root@test ~]#
[root@test ~]# systemctl restart nginx
[root@test ~]# vi /var/www/html/test.com/public_html/index.php
<?php phpinfo(); ?>

 

 

6. web-site 접속테스트

 

mysqldump-max_allowed_packet error

max_allowed_packet error 발생시 –max_allowed_packet=1024M 옵션을 사용 하면 됩니다.

[root@localhost ~]# mysqldump -uroot -p --all-databases > db-data.sql
Enter password:
mysqldump: Error 2020: Got packet bigger than 'max_allowed_packet' bytes when dumping table `wp_aiowps_global_meta` at row: 1
[root@localhost ~]# mysqldump -uroot -p --all-databases --max_allowed_packet=1024M > db-data.sql
Enter password:
[root@localhost ~]#

 

 

rancher 설치

Official site docs : https://rancher.com/docs/rancher/v2.x/en/ 

참고: https://rancher.com/docs/rancher/v2.x/en/installation/single-node/single-node-install-external-lb/ 

docker-compose 를 이용하여 blog 및 docs Site 를 운영 하고 있습니다.

사용량이 적은 Micro service 의 경우 크게 문제는 없지만 서비스가 늘어 갈수록 다소 부족함을 느껴

뒤늦게 알게된 rancher 를 테스트 하고 있습니다.

일반적인 설치와 기본 기능들만 테스트 하며 여러대의 docker 의 경우 별도로 포스팅 하겠습니다.

 

1.docker 삭제후 재설치

rancher 에서 지원 하지 않는 docker version 을 사용할 경우 docker 를 삭제 합니다.

[root@CentOS7 ~]# yum remove docker-ce-*
[root@CentOS7 ~]# curl https://releases.rancher.com/install-docker/18.06.sh | sh
[root@CentOS7 ~]# docker version
Client:
 Version:           18.06.3-ce
 API version:       1.38
 Go version:        go1.10.3
 Git commit:        d7080c1
 Built:             Wed Feb 20 02:26:51 2019
 OS/Arch:           linux/amd64
 Experimental:      false

Server:
 Engine:
  Version:          18.06.3-ce
  API version:      1.38 (minimum version 1.12)
  Go version:       go1.10.3
  Git commit:       d7080c1
  Built:            Wed Feb 20 02:28:17 2019
  OS/Arch:          linux/amd64
  Experimental:     false
[root@CentOS7 ~]#

 

 

 

2.rancher 설치

주의!!! rancher 에서 지원 하는 docker Version 을 사용 해야 합니다.

[root@CentOS7 ~]# docker run -d --restart=unless-stopped -p 8080:8080 rancher/server

설치 완료
[root@CentOS7 ~]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                              NAMES
fda18a057b90        rancher/server      "/usr/bin/entry /usr…"   11 seconds ago      Up 9 seconds        3306/tcp, 0.0.0.0:8080->8080/tcp   admiring_meitner
[root@CentOS7 ~]#

 

 

3. host:8080 으로 접속 합니다.

 

4.INFRASTRUCTURE 를 클릭합니다.

 

5. Add Host 를 클릭합니다.

 

6. Save 를 클릭 합니다.

테스트로는 Single node 로 테스트 합니다.

 

7.IP 정보를 입력합니다.

 

8.스크립트를 복사하여 실행 합니다.

 

9. 터미널 에서 스크립트를 실행 합니다.

[root@CentOS7 ~]# sudo docker run -e CATTLE_AGENT_IP="192.168.0.10"  --rm --privileged -v /var/run/docker.sock:/var/run/docker.sock -v /var/lib/rancher:/var/lib/rancher \
rancher/agent:v1.2.11 http://192.168.0.10:8080/v1/scripts/E0A2CBD52872D58CC86C:1546214400000:EIL0DLMlcfxqiOLg3bxlr9chelc

 

 

10. rancher agent 확인

[root@CentOS7 ~]# docker ps
CONTAINER ID        IMAGE                   COMMAND                  CREATED             STATUS              PORTS                              NAMES
fc16c6b8a09c        rancher/agent:v1.2.11   "/run.sh run"            4 seconds ago       Up 3 seconds                                           rancher-agent
fda18a057b90        rancher/server          "/usr/bin/entry /usr…"   12 minutes ago      Up 12 minutes       3306/tcp, 0.0.0.0:8080->8080/tcp   admiring_meitner
[root@CentOS7 ~]#

 

 

11. rancher 상태 확인

rancher agent 가 설치 되고 나면 INFRASTRUCTURE 에서 상태를 확인 할수 있습니다.

정상구동이 안될시 docker version 을 확인 해야 하며, docker 재설치가 필요 합니다.

rancher 지원 docker version 확인 https://rancher.com/docs/rancher/v1.6/en/hosts/#supported-docker-versions 에서 확인할수 있습니다.

 

12. rancher 확인

single node 구성시 INFRASTRUCTURE 에서 상태를 확인 할수 있습니다.

 

13. rancher nginx 컨테이너 생성

rancher 를 이용하여 nginx 컨테이너를 생성 합니다. 사전작업으로는 디렉토리 생성 및 nginx config 파일을 생성 해야 합니다.

[root@CentOS7 ~]# mkdir -p /Workspace/nginx/conf
[root@CentOS7 ~]# mkdir /Workspace/wiki
[root@CentOS7 ~]# vi /Workspace/nginx/conf/default.conf
server {
    listen       80 default_server;
    server_name  localhost _;
    index        index.html index.htm;
    root         /code;

    location / {
        autoindex on;
    }
}

 

 

14.rancher 에 접속 하여 Service 를 생성 합니다.

Default -> Default 를 클릭하여 Stack 매뉴어 들어 갑니다.

Add Service 를 클릭하여 nginx Service 를 생성 합니다.

 

 

15. Add Service 생성

Name / Select Image / port Map 를 설정합니다.

 

16. Volumes 탭 설정

기존에 생성해 놓은 디렉토리를 연결 합니다.

 

17. Nginx Service 상태 확인

Create 를 클릭하면 rancher 에서 컨테이너를 생성 합니다.

  • nginx 컨테이너를 생성중입니다.

 

  • nginx 컨테이너를 생성 완료 하였습니다.

 

  • web-site 확인

IP 로 접속하면 nginx Default 디렉토리인 /Workspace/wiki 디렉토리 내용을 확인 할수 있습니다.

간단한 docs 를 운영할때는 이정도 설정이면 충분 합니다.

NFS Persistent Volume

NFS Persistent Volume 을 생성 합니다. Test 시 사용할 서비스는 mysql 과 wordpress 입니다.

테스트시 아래와 동일하게 설정해도 무방 하지만 온프레미스 에서 서비스를 하신다면 기본적으로 Storage 라인을 분리해야 하며, NFS 라인은 10G Network 를 이용해야 합니다.

참고페이지: https://docs.okd.io/latest/install_config/persistent_storage/persistent_storage_nfs.html

 

 

  • nfs-Server(storage) 설정

별도의 vm 에 nfs-utils 를 설치 하고 /data 디렉토리를 공유 합니다.

[root@k8s-storage ~]# yum install -y nfs-utils
[root@k8s-storage ~]# mkdir -p /data/{mysql,html}
[root@k8s-storage ~]#  chmod -R 755 /data
[root@k8s-storage ~]#  chown -R nfsnobody:nfsnobody /data/

[root@k8s-storage ~]# vi /etc/exports
/data/html      *(rw,sync,no_root_squash)
/data/mysql     *(rw,sync,no_root_squash)
[root@k8s-storage ~]#

[root@k8s-storage ~]#  systemctl enable nfs-server ; systemctl start nfs-server
[root@k8s-storage ~]#  systemctl status nfs-server

 

 

  • nfs-utils 패키지설치

nfs-utils 패키지를 모든노드에 설치 합니다.

k8s-master 설치
[root@k8s-master ~]# yum install -y nfs-utils 

k8s-node01 설치 
[root@k8s-node01 ~]# yum install nfs-utils 

k8s-node02 설치 
[root@k8s-node01 ~]# yum install nfs-utils

 

 

  • wordpress 작업 디렉토리 생성
[root@k8s-master ~]# mkdir wordpress
[root@k8s-master ~]# cd wordpress

 

 

 

  • pv-wordpress.yml 파일 생성

wordpress 와 mysql 에서 사용할 Persistent Volume 을 생성 합니다.

[root@k8s-master wordpress]# vi pv-wordpress.yaml
kind: PersistentVolume
apiVersion: v1
metadata:
  name: wordpress-volume
  labels:
    type: local
spec:
  capacity:
    storage: 10Gi
  accessModes:
    - ReadWriteMany
  nfs:
    server: 10.10.10.18
    # Exported path of your NFS server
    path: "/data/html"
 
---
kind: PersistentVolume
apiVersion: v1
metadata:
  name: mysql-volume
  labels:
    type: local
spec:
  capacity:
    storage: 10Gi
  accessModes:
    - ReadWriteMany
  nfs:
    server: 10.10.10.18
    # Exported path of your NFS server
    path: "/data/mysql"

 

 

 

  • pv-wordpress 생성

pv-wordpress.yaml 파일을 이용하여 Persistent Volume 을 생성 합니다.

[root@k8s-master wordpress]# kubectl create -f pv-wordpress.yaml
persistentvolume/wordpress-volume created
persistentvolume/mysql-volume created
[root@k8s-master wordpress]#



[root@k8s-master wordpress]# kubectl get pv
NAME               CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS      CLAIM   STORAGECLASS   REASON   AGE
mysql-volume       10Gi       RWX            Retain           Available                                   15s
wordpress-volume   10Gi       RWX            Retain           Available                                   15s
[root@k8s-master wordpress]#

 

 

 

  • pvc-wordpress.yaml 파일 생성

Persistent Volume Claim 을 생성 합니다.

[root@k8s-master wordpress]# vi pvc-wordpress.yaml
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: wordpress-volumeclaim
spec:
  accessModes:
    - ReadWriteMany
  resources:
    requests:
 
      storage: 10Gi
 
 

---
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: mysql-volumeclaim
spec:
  accessModes:
    - ReadWriteMany
  resources:
    requests:
 
      storage: 10Gi

 

 

  • pvc-wordpress 생성

pvc-wordpress.yaml 파일을 이용하여 Persistent Volume Claim 을 생성 합니다.

[root@k8s-master wordpress]# kubectl create -f pvc-wordpress.yaml
persistentvolumeclaim/wordpress-volumeclaim created
persistentvolumeclaim/mysql-volumeclaim created
[root@k8s-master wordpress]#


[root@k8s-master wordpress]# kubectl get pvc
NAME                    STATUS   VOLUME             CAPACITY   ACCESS MODES   STORAGECLASS   AGE
mysql-volumeclaim       Bound    mysql-volume       10Gi       RWX                           6s
wordpress-volumeclaim   Bound    wordpress-volume   10Gi       RWX                           6s
[root@k8s-master wordpress]#

 

 

  • mysql-password 생성
  • secret 삭제시 kubectl delete secret mysql-password
[root@k8s-master wordpress]# kubectl create secret generic mysql-password --from-literal=password=mysqlpassword
secret/mysql-password created
[root@k8s-master wordpress]# kubectl describe secret mysql-password
Name:         mysql-password
Namespace:    default
Labels:       <none>
Annotations:  <none>
 
Type:  Opaque
 
Data
====
password:  13 bytes
[root@k8s-master wordpress]#

 

 

 

  • mysql pod 파일 생성
[root@k8s-master wordpress]# vi mysql.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: mysql
  labels:
    app: mysql
spec:
  replicas: 1
  selector:
    matchLabels:
      app: mysql
  template:
    metadata:
      labels:
        app: mysql
    spec:
      containers:
        - image: mysql:5.6
          name: mysql
          env:
            - name: MYSQL_ROOT_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: mysql-password
                  key: password
            - name: MYSQL_DATABASE 
              value: wordpress         # WP 에서 사용할 DB명
            - name: MYSQL_USER
              value: wordpress         # WP 에서 사용할 USER명
            - name: MYSQL_ROOT_HOST
              value: '%'
            - name: MYSQL_PASSWORD 
              value: wordpress         # WP 데이터베이스 Password
          ports:
            - containerPort: 3306
              name: mysql
          volumeMounts:
            - name: mysql-persistent-storage
              mountPath: /var/lib/mysql
      volumes:
        - name: mysql-persistent-storage
          persistentVolumeClaim:
            claimName: mysql-volumeclaim

 

 

  • mysql pods 생성
[root@k8s-master wordpress]# kubectl create -f mysql.yaml
deployment.apps/mysql created
[root@k8s-master wordpress]# kubectl get pods -o wide
NAME                     READY   STATUS              RESTARTS   AGE   IP       NODE         NOMINATED NODE   READINESS GATES
mysql-5d4c989597-w9s2s   0/1     ContainerCreating   0          6s    <none>   k8s-node01   <none>           <none>
 
약 1~2분 소요 됩니다. 
[root@k8s-master wordpress]# kubectl get pods -o wide
NAME                     READY   STATUS    RESTARTS   AGE   IP          NODE         NOMINATED NODE   READINESS GATES
mysql-5d4c989597-w9s2s   1/1     Running   0          34s   20.20.2.2   k8s-node01   <none>           <none>
[root@k8s-master wordpress]#

 

 

  • mysql svc 생성
[root@k8s-master wordpress]# vi mysql-service.yaml
apiVersion: v1
 
kind: Service
metadata:
  name: mysql
  labels:
    app: mysql
spec:
  type: ClusterIP
  ports:
    - port: 3306
  selector:
    app: mysql
 
[root@k8s-master wordpress]# kubectl create -f mysql-service.yaml
service/mysql created
[root@k8s-master wordpress]#
 
 
[root@k8s-master wordpress]# kubectl get svc -o wide
NAME         TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)    AGE   SELECTOR
kubernetes   ClusterIP   10.96.0.1       <none>        443/TCP    82d   <none>
mysql        ClusterIP   10.102.149.39   <none>        3306/TCP   7s    app=mysql
[root@k8s-master wordpress]#

 

 

  • wordpress pod 생성
[root@k8s-master wordpress]# vi wordpress.yaml
apiVersion: apps/v1
 
kind: Deployment
metadata:
  name: wordpress
  labels:
    app: wordpress
spec:
  replicas: 1
  selector:
    matchLabels:
      app: wordpress
  template:
    metadata:
      labels:
        app: wordpress
    spec:
      containers:
        - image: wordpress
          name: wordpress
          env:
          - name: WORDPRESS_DB_HOST
            value: mysql:3306
          - name: WORDPRESS_DB_NAME
            value: wordpress
          - name: WORDPRESS_DB_USER
            value: wordpress
          - name: WORDPRESS_DB_PASSWORD
            value: wordpress
          ports:
            - containerPort: 80
              name: wordpress
          volumeMounts:
            - name: wordpress-persistent-storage
              mountPath: /var/www/html
      volumes:
        - name: wordpress-persistent-storage
          persistentVolumeClaim:
            claimName: wordpress-volumeclaim
 
 
[root@k8s-master wordpress]# kubectl create -f wordpress.yaml
deployment.apps/wordpress created
[root@k8s-master wordpress]# kubectl get pods
NAME                         READY   STATUS              RESTARTS   AGE
NAME                         READY   STATUS    RESTARTS   AGE
mysql-6845698854-46pmx       1/1     Running   0          2m12s
wordpress-74747f4dbf-fbbnh   1/1     Running   0          12s
 
[root@k8s-master wordpress]#

 

 

  • wordpress svc 생성
[root@k8s-master wordpress]# vi wordpress-service.yaml
apiVersion: v1
kind: Service
metadata:
  labels:
    app: wordpress
  name: wordpress
spec:
  type: NodePort
  ports:
    - port: 80
      targetPort: 80
      protocol: TCP
  selector:
    app: wordpress
 
[root@k8s-master wordpress]# kubectl create -f wordpress-service.yaml
service/wordpress created
[root@k8s-master wordpress]#
 
 
[root@k8s-master wordpress]# kubectl get svc -o wide
NAME         TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE   SELECTOR
kubernetes   ClusterIP   10.96.0.1       <none>        443/TCP        95d   <none>
mysql        ClusterIP   10.99.245.34    <none>        3306/TCP       65s   app=mysql
wordpress    NodePort    10.104.25.182   <none>        80:31868/TCP   4s    app=wordpress
[root@k8s-master wordpress]#

 

 

 

 

 

wordpress mysql Persistent Volume 배포

kubernetes 에서 Persistent Volume 을 이용하여 wordpress , mysql 을 Persistent Volume 에 배포 합니다.

참고페이지: https://cloud.google.com/kubernetes-engine/docs/tutorials/persistent-disk?hl=ko

https://kubernetes.io/ko/docs/tutorials/stateful-application/mysql-wordpress-persistent-volume/#mysql과-wordpress에-필요한-리소스-구성-추가하기

 

 

1. kubernetes Service 확인

[root@k8s-master ~]# kubectl get pods --all-namespaces
NAMESPACE NAME READY STATUS RESTARTS AGE
kube-system calico-node-fcbq8 2/2 Running 2 81d
kube-system calico-node-kzqlv 2/2 Running 2 81d
kube-system calico-node-r8ggc 2/2 Running 2 81d
kube-system coredns-fb8b8dccf-4zq8l 1/1 Running 1 81d
kube-system coredns-fb8b8dccf-fg9l7 1/1 Running 1 81d
kube-system etcd-k8s-master 1/1 Running 1 81d
kube-system kube-apiserver-k8s-master 1/1 Running 1 81d
kube-system kube-controller-manager-k8s-master 1/1 Running 1 81d
kube-system kube-proxy-ph9np 1/1 Running 1 81d
kube-system kube-proxy-x28cx 1/1 Running 1 81d
kube-system kube-proxy-z252g 1/1 Running 1 81d
kube-system kube-scheduler-k8s-master 1/1 Running 1 81d
kube-system kubernetes-dashboard-5f7b999d65-qmjfx 1/1 Running 1 81d
[root@k8s-master ~]#

 

 

2. Persistent Volume 생성

wordpress 와 mysql 에서 사용할 Persistent Volume 을 지정 합니다.

[root@k8s-master wordpress]# vi web01.yaml
kind: PersistentVolume
apiVersion: v1
metadata:
  name: web01
  labels:
    type: local
spec:
  capacity:
    storage: 5Gi
  accessModes:
    - ReadWriteOnce
  hostPath:

    path: "/data/web01"



[root@k8s-master wordpress]# vi db01.yaml
kind: PersistentVolume
apiVersion: v1
metadata:
  name: db01
  labels:
    type: local
spec:
  capacity:
    storage: 5Gi
  accessModes:
    - ReadWriteOnce
  hostPath:
    path: "/data/db01"

[root@k8s-master wordpress]# kubectl create -f web01.yaml
persistentvolume/web01 created
[root@k8s-master wordpress]# kubectl create -f db01.yaml
persistentvolume/db01 created
[root@k8s-master wordpress]# kubectl get pv
NAME    CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS      CLAIM   STORAGECLASS   REASON   AGE
db01    5Gi        RWO            Retain           Available                                   3s
web01   5Gi        RWO            Retain           Available                                   8s
[root@k8s-master wordpress]#

 

 

3. Persistent Volume Claim 생성

[root@k8s-master wordpress]# vi wordpress-vol.yaml
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: wordpress-volumeclaim
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:

      storage: 5Gi
[root@k8s-master wordpress]# vi mysql-vol.yaml
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: mysql-volumeclaim
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:

      storage: 5Gi

[root@k8s-master wordpress]# kubectl create -f wordpress-vol.yaml
persistentvolumeclaim/wordpress-volumeclaim created
[root@k8s-master wordpress]# kubectl create -f mysql-vol.yaml
persistentvolumeclaim/mysql-volumeclaim created
[root@k8s-master wordpress]# kubectl get pvc
NAME                    STATUS   VOLUME   CAPACITY   ACCESS MODES   STORAGECLASS   AGE
mysql-volumeclaim       Bound    db01     5Gi        RWO                           4s
wordpress-volumeclaim   Bound    web01    5Gi        RWO                           11s
[root@k8s-master wordpress]#

 

 

 

 

4. mysql root password 생성

secret 삭제시 kubectl delete secret mysql-password

[root@k8s-master wordpress]# kubectl create secret generic mysql-password --from-literal=password=mysqlpassword
secret/mysql-password created
[root@k8s-master wordpress]# kubectl describe secret mysql-password
Name:         mysql-password
Namespace:    default
Labels:       <none>
Annotations:  <none>

Type:  Opaque

Data
====
password:  13 bytes
[root@k8s-master wordpress]#

 

 

5. mysql pod 생성

wordpress 에서 사용할 DB 와 DB 사용자 / Password 를 지정 합니다.

[root@k8s-master wordpress]# vi mysql.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: mysql
  labels:
    app: mysql
spec:
  replicas: 1
  selector:
    matchLabels:
      app: mysql
  template:
    metadata:
      labels:
        app: mysql
    spec:
      containers:
        - image: mysql:5.6
          name: mysql
          env:
            - name: MYSQL_ROOT_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: mysql-password
                  key: password
            - name: MYSQL_DATABASE 
              value: wordpress         # WP 에서 사용할 DB명
            - name: MYSQL_USER
              value: wordpress         # WP 에서 사용할 USER명
            - name: MYSQL_ROOT_HOST
              value: '%'
            - name: MYSQL_PASSWORD 
              value: wordpress         # WP 데이터베이스 Password
          ports:
            - containerPort: 3306
              name: mysql
          volumeMounts:
            - name: mysql-persistent-storage
              mountPath: /var/lib/mysql
      volumes:
        - name: mysql-persistent-storage
          persistentVolumeClaim:
            claimName: mysql-volumeclaim


[root@k8s-master wordpress]# kubectl create -f mysql.yaml
deployment.apps/mysql created
[root@k8s-master wordpress]# kubectl get pods -o wide
NAME                     READY   STATUS    RESTARTS   AGE   IP           NODE         NOMINATED NODE   READINESS GATES
mysql-6845698854-46pmx   1/1     Running   0          4s    20.20.2.10   k8s-node02   <none>           <none>
[root@k8s-master wordpress]#

 

 

 

6. mysq-service 생성

[root@k8s-master wordpress]# vi mysql-service.yaml
apiVersion: v1

kind: Service
metadata:
  name: mysql
  labels:
    app: mysql
spec:
  type: ClusterIP
  ports:
    - port: 3306
  selector:
    app: mysql
[root@k8s-master wordpress]# kubectl create -f mysql-service.yaml
service/mysql created
[root@k8s-master wordpress]# kubectl get svc
NAME         TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)    AGE
kubernetes   ClusterIP   10.96.0.1        <none>        443/TCP    10d
mysql        ClusterIP   10.109.232.234   <none>        3306/TCP   3s
[root@k8s-master wordpress]#

 

 

7. wordpress pod 생성

[root@k8s-master wordpress]# vi wordpress.yaml
apiVersion: apps/v1

kind: Deployment
metadata:
  name: wordpress
  labels:
    app: wordpress
spec:
  replicas: 1
  selector:
    matchLabels:
      app: wordpress
  template:
    metadata:
      labels:
        app: wordpress
    spec:
      containers:
        - image: wordpress
          name: wordpress
          env:
          - name: WORDPRESS_DB_HOST
            value: mysql:3306
          - name: WORDPRESS_DB_NAME
            value: wordpress
          - name: WORDPRESS_DB_USER
            value: wordpress
          - name: WORDPRESS_DB_PASSWORD
            value: wordpress
          ports:
            - containerPort: 80
              name: wordpress
          volumeMounts:
            - name: wordpress-persistent-storage
              mountPath: /var/www/html
      volumes:
        - name: wordpress-persistent-storage
          persistentVolumeClaim:
            claimName: wordpress-volumeclaim


[root@k8s-master wordpress]# kubectl create -f wordpress.yaml
deployment.apps/wordpress created
[root@k8s-master wordpress]# kubectl get pods
NAME                         READY   STATUS              RESTARTS   AGE
NAME                         READY   STATUS    RESTARTS   AGE
mysql-6845698854-46pmx       1/1     Running   0          2m12s
wordpress-74747f4dbf-fbbnh   1/1     Running   0          12s

[root@k8s-master wordpress]#

 

 

8. wordpress-service 생성

[root@k8s-master wordpress]# vi wordpress-service.yaml
apiVersion: v1
kind: Service
metadata:
  labels:
    app: wordpress
  name: wordpress
spec:
  type: NodePort
  ports:
    - port: 80
      targetPort: 80
      protocol: TCP
  selector:
    app: wordpress
[root@k8s-master wordpress]# kubectl create -f wordpress-service.yaml
service/wordpress created
[root@k8s-master wordpress]# kubectl get svc -o wide
NAME         TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)        AGE     SELECTOR
kubernetes   ClusterIP   10.96.0.1        <none>        443/TCP        10d     <none>
mysql        ClusterIP   10.111.162.117   <none>        3306/TCP       5m56s   app=mysql
wordpress    NodePort    10.107.48.226    <none>        80:30950/TCP   5m24s   app=wordpress
[root@k8s-master wordpress]#

 

 

 

k8s-master:30950 로 접속 하여 확인 가능 합니다.

k9s-master 는 192.168.0.10입니다.

 

 

CentOS7 minikube 설치

참고 페이지 : https://kubernetes.io/ko/docs/tasks/tools/install-minikube/

https://computingforgeeks.com/how-to-run-minikube-on-kvm/

kvm 환경에서 minikube 설치 방법을 정리 하였습니다. Virtualbox 및 vmware 에서는 kubernetes 3 node 구성이 좀더 편하게 설치 됩니다. 🙂

 

 

1. 가상화 지원 확인

[root@kvm-server01 ~]# grep -E --color 'vmx|svm' /proc/cpuinfo
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall
nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf eagerfpu pni pclmulqdq dtes64 monitor ds_cp
l vmx smx est tm2 ssse3 cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic popcnt aes lahf_lm ssbd ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid
dtherm ida arat spec_ctrl intel_stibp flush_l1d
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall
nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf eagerfpu pni pclmulqdq dtes64 monitor ds_cp
l vmx smx est tm2 ssse3 cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic popcnt aes lahf_lm ssbd ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid
dtherm ida arat spec_ctrl intel_stibp flush_l1d
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall
nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf eagerfpu pni pclmulqdq dtes64 monitor ds_cp
l vmx smx est tm2 ssse3 cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic popcnt aes lahf_lm ssbd ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid
dtherm ida arat spec_ctrl intel_stibp flush_l1d
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall
nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf eagerfpu pni pclmulqdq dtes64 monitor ds_cp
l vmx smx est tm2 ssse3 cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic popcnt aes lahf_lm ssbd ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid
dtherm ida arat spec_ctrl intel_stibp flush_l1d
~ 중략

 

 

2. Download minikube

[root@kvm-server01 ~]# wget https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64
[root@kvm-server01 ~]# chmod +x minikube-linux-amd64
[root@kvm-server01 ~]# mv minikube-linux-amd64 /usr/local/bin/minikube
[root@kvm-server01 ~]# minikube version
minikube version: v1.3.1
commit: ca60a424ce69a4d79f502650199ca2b52f29e631
[root@kvm-server01 ~]#

 

 

3. Install kubectl

[root@kvm-server01 ~]# curl -LO https://storage.googleapis.com/kubernetes-release/release/`curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt`/bin/linux/amd64/kubectl
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 40.9M 100 40.9M 0 0 29.0M 0 0:00:01 0:00:01 --:--:-- 29.0M
[root@kvm-server01 ~]# chmod +x kubectl
[root@kvm-server01 ~]# mv kubectl /usr/local/bin/
[root@kvm-server01 ~]# kubectl version -o json
{
"clientVersion": {
"major": "1",
"minor": "15",
"gitVersion": "v1.15.3",
"gitCommit": "2d3c76f9091b6bec110a5e63777c332469e0cba2",
"gitTreeState": "clean",
"buildDate": "2019-08-19T11:13:54Z",
"goVersion": "go1.12.9",
"compiler": "gc",
"platform": "linux/amd64"
}
}
The connection to the server localhost:8080 was refused - did you specify the right host or port?
[root@kvm-server01 ~]#

 

 

4. Install Docker Machine KVM Driver

[root@kvm-server01 ~]# curl -LO https://storage.googleapis.com/minikube/releases/latest/docker-machine-driver-kvm2
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 13.8M 100 13.8M 0 0 13.4M 0 0:00:01 0:00:01 --:--:-- 13.5M
[root@kvm-server01 ~]#
[root@kvm-server01 ~]# chmod +x docker-machine-driver-kvm2
[root@kvm-server01 ~]# mv docker-machine-driver-kvm2 /usr/local/bin/

Starting minikube

[root@kvm-server01 ~]# chmod +x docker-machine-driver-kvm2
[root@kvm-server01 ~]# mv docker-machine-driver-kvm2 /usr/local/bin/
[root@kvm-server01 ~]# minikube start --vm-driver kvm2
* minikube v1.3.1 on Centos 7.6.1810
! Please don't run minikube as root or with 'sudo' privileges. It isn't necessary with kvm2 driver.
* Downloading VM boot image ...
minikube-v1.3.0.iso.sha256: 65 B / 65 B [--------------------] 100.00% ? p/s 0s
minikube-v1.3.0.iso: 131.07 MiB / 131.07 MiB [-------] 100.00% 48.99 MiB p/s 3s
* Creating kvm2 VM (CPUs=2, Memory=2000MB, Disk=20000MB) ...
* Preparing Kubernetes v1.15.2 on Docker 18.09.8 ...
* Downloading kubeadm v1.15.2
* Downloading kubelet v1.15.2
* Pulling images ...
* Launching Kubernetes ...
* Waiting for: apiserver proxy etcd scheduler controller dns
* Done! kubectl is now configured to use "minikube"
[root@kvm-server01 ~]#


[root@kvm-server01 ~]# sudo virsh list |grep mini
320 minikube running
[root@kvm-server01 ~]#

[root@kvm-server01 ~]# kubectl cluster-info
Kubernetes master is running at https://192.168.39.228:8443
KubeDNS is running at https://192.168.39.228:8443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy

To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.
[root@kvm-server01 ~]#


[root@kvm-server01 ~]# kubectl config view
apiVersion: v1
clusters:
- cluster:
certificate-authority: /root/.minikube/ca.crt
server: https://192.168.39.228:8443
name: minikube
contexts:
- context:
cluster: minikube
user: minikube
name: minikube
current-context: minikube
kind: Config
preferences: {}
users:
- name: minikube
user:
client-certificate: /root/.minikube/client.crt
client-key: /root/.minikube/client.key
[root@kvm-server01 ~]#


[root@kvm-server01 ~]# kubectl get nodes
NAME STATUS ROLES AGE VERSION
minikube Ready master 15m v1.15.2
[root@kvm-server01 ~]# minikube ssh
_ _
_ _ ( ) ( )
___ ___ (_) ___ (_)| |/') _ _ | |_ __
/' _ ` _ `\| |/' _ `\| || , < ( ) ( )| '_`\ /'__`\
| ( ) ( ) || || ( ) || || |\`\ | (_) || |_) )( ___/
(_) (_) (_)(_)(_) (_)(_)(_) (_)`\___/'(_,__/'`\____)

$ cat /etc/os-release
NAME=Buildroot
VERSION=2018.05.3
ID=buildroot
VERSION_ID=2018.05.3
PRETTY_NAME="Buildroot 2018.05.3"
$

 

 

VM 을 이용한 테스트를 하다 보면 최소 설치후 패키지 설치 하는 작업등 동일한 설치 작업을 많이 합니다.

Vagrantfile 을 이용하면 손쉽게 vm 을 생성 할수 있습니다.

본 문서에서는 Test VM 생성까지만 소개 합니다. 🙂

1. vagrant 명령어

vagrant list-commands 로 vagrant 명령어를 확인 할수 있습니다.

$ vagrant.exe list-commands
Below is a listing of all available Vagrant commands and a brief
description of what they do.

box             manages boxes: installation, removal, etc.
cap             checks and executes capability
cloud           manages everything related to Vagrant Cloud
destroy         stops and deletes all traces of the vagrant machine
docker-exec     attach to an already-running docker container
docker-logs     outputs the logs from the Docker container
docker-run      run a one-off command in the context of a container
global-status   outputs status Vagrant environments for this user
halt            stops the vagrant machine
help            shows the help for a subcommand
init            initializes a new Vagrant environment by creating a Vagrantfile
list-commands   outputs all available Vagrant subcommands, even non-primary ones
login
package         packages a running vagrant environment into a box
plugin          manages plugins: install, uninstall, update, etc.
port            displays information about guest port mappings
powershell      connects to machine via powershell remoting
provider        show provider for this environment
provision       provisions the vagrant machine
push            deploys code in this environment to a configured destination
rdp             connects to machine via RDP
reload          restarts vagrant machine, loads new Vagrantfile configuration
resume          resume a suspended vagrant machine
rsync           syncs rsync synced folders to remote machine
rsync-auto      syncs rsync synced folders automatically when files change
snapshot        manages snapshots: saving, restoring, etc.
ssh             connects to machine via SSH
ssh-config      outputs OpenSSH valid configuration to connect to the machine
status          outputs status of the vagrant machine
suspend         suspends the machine
up              starts and provisions the vagrant environment
upload          upload to machine via communicator
validate        validates the Vagrantfile
vbguest         plugin: vagrant-vbguest: install VirtualBox Guest Additions to the machine
version         prints current and latest Vagrant version
winrm           executes commands on a machine via WinRM
winrm-config    outputs WinRM configuration to connect to the machine

 

 

1.1 vagrant 기본 명령어

일반적으로 많이 사용 하는 명령어를 소개 합니다.

Vagrant 명령어 설명
vagrant init 디렉토리에 Vagrantfile 을 생성 합니다.
vagrant up Vagrantfile 에서 VM 을 생성 합니다.
vagrant ssh vm 연결시 사용 합니다.
vagrant halt vm 을 정지 합니다.
vagrant destroy 생성된 vm 을 삭제 합니다.
vagrant provision vm 에 프로비저닝 합니다.
box add $배포판 Vagrant box 를 다운로드 합니다.
box list 다운로드된 Vagrant box 를 확인 합니다.

 

2. Vagrantfile 작성 참고사항

외부 접속이 필요 없다면 NAT Network 로만 VM 을 구성 하여도 됩니다.

Vagrant.configure("2") do |config|
  config.vm.box = "centos/7"                                           <--- vagrant box 지정 centos / ubuntu 등


network 설정
  config.vm.network "public_network"                                   <--- Bridge Network 사용시 
  config.vm.network "private_network", ip: "192.168.33.10"             <--- NAT Network 사용시


Virtualbox 설정  
   config.vm.provider "virtualbox" do |vb|
   vb.name="CentOS7"                                                    <--- Virtualbox VM name 



프로비저닝 할때는 아래와 같이 vagrant provision 옵션을 사용 합니다. 
sanjuk@testMachine MINGW64 ~/HashiCorp/centos
$ vagrant.exe provision


Provision 설정                                                                   
  config.vm.provision "shell", inline: <<-SHELL
  #   apt-get update
  #   apt-get install -y apache2
  # SHELL
  yum -y update                                                          <---- 설치할 패키지를 지정 
  yum -y install wget
  yum -y install net-tools
  yum -y install bind-utils
  yum -y install epel-release
  wget http://rpms.famillecollet.com/enterprise/remi-release-7.rpm
  rpm -Uvh remi-release-7.rpm
  SHELL
end

 

 

Virtualbox + Vagrant 설치

평소 테스트 환경을 구축 할때 KVM 을 이용하여 virt-clone qemu-img 를 사용하여 Test 머신을 생성 하였습니다.

Vagrant 를 이용하면 vagrantfile 을 이용하여 쉽고 빠르게 테스트 환경을 구성 할수 있습니다.

vmware 의 경우 별도의 라이센스를 구입하여야 사용 가능합니다.

   1. Virtualbox 설치

site: https://www.virtualbox.org/wiki/Downloads   에 접속하여 VirtualBox 를 다운받아 설치 합니다. 

Windows 에서 ssh 를 통한 접속을 위해 VirtualBox Extension Pack 도 설치 합니다.

VirtualBox Extension Pack 의 경우 VirutlaBox 설치후 더블 클릭으로 설치 할수 있습니다.

 

 

   2. Vagrant 설치

site : https://www.vagrantup.com/downloads.html   에서 다운받아 설치를 진행 합니다.

Default 설치를 진행 하였을 경우 c:\HashiCorp 에 설치 됩니다.

터미널은 git bash 를 사용 하였습니다. https://gitforwindows.org/

vagraint init 로 Vagrantfile 을 생성 합니다.

sanjuk@DESKTOP-O1Q8NLC MINGW64 /c/HashiCorp
$ mkdir centos

sanjuk@DESKTOP-O1Q8NLC MINGW64 /c/HashiCorp
$ cd centos/

sanjuk@DESKTOP-O1Q8NLC MINGW64 /c/HashiCorp/centos
$ vagrant init
A `Vagrantfile` has been placed in this directory. You are now
ready to `vagrant up` your first virtual environment! Please read
the comments in the Vagrantfile as well as documentation on
`vagrantup.com` for more information on using Vagrant.

sanjuk@DESKTOP-O1Q8NLC MINGW64 /c/HashiCorp/centos
$

 

   3. Vagrantfile 수정

처음으로 vagrant를 생성 하기 위하여 Vagrantfile 을 수정 합니다.

Vagrant.configure("2") do |config|
  # The most common configuration options are documented and commented below.
  # For a complete reference, please see the online documentation at
  # https://docs.vagrantup.com.

  # Every Vagrant development environment requires a box. You can search for
  # boxes at https://vagrantcloud.com/search.
  config.vm.box = "centos/7"   <-- vm 이미지를 centos7 로 지정 하였습니다.

 

4.1 Vagrant add box

Vagrant box add $boxname 를 하여 사용할 box 를 다운로드 할수 있습니다.

https://app.vagrantup.com/boxes/search site 에서 box 검색할수 있습니다.

# 테스트를 위하여 centos7 박스를 다운로드 합니다. 
$ vagrant box add centos/7
==> box: Loading metadata for box 'centos/7'
    box: URL: https://vagrantcloud.com/centos/7
This box can work with multiple providers! The providers that it
can work with are listed below. Please review the list and choose
the provider you will be working with.

1) hyperv
2) libvirt
3) virtualbox
4) vmware_desktop

Enter your choice: 3
==> box: Adding box 'centos/7' (v1905.1) for provider: virtualbox
    box: Downloading: https://vagrantcloud.com/centos/boxes/7/versions/1905.1/providers/virtualbox.box
==> box: Box download is resuming from prior download progress
    box: Download redirected to host: cloud.centos.org
    box:
==> box: Successfully added box 'centos/7' (v1905.1) for 'virtualbox'!

sanjuk@DESKTOP-O1Q8NLC MINGW64 /c/HashiCorp/centos
$ vagrant box list
centos/7 (virtualbox, 1905.1)

sanjuk@DESKTOP-O1Q8NLC MINGW64 /c/HashiCorp/centos

 

4.2 Vagrantfile 을 이용한 box 생성

테스트를 위하여 centos7 박스를 생성합니다.

간편하게  vagrant up 명령어를 통하여 VM 을 생성 할수 있습니다.

$ vagrant up

 

4.3 vagrant-vbguest 설치

$ vagrant plugin install vagrant-vbguest
Installing the 'vagrant-vbguest' plugin. This can take a few minutes...
Installed the plugin 'vagrant-vbguest (0.19.0)'!

 

vagrant 생성전

 

vagrant 생성후

 

5. vagrant 접속

vargrant ssh 명령어로 접속 할수 있습니다.

sanjuk@DESKTOP-1HGOOGJ MINGW64 ~/HashiCorp/centos
$ vagrant ssh
[vagrant@localhost ~]$

 

가상머신에서는 vagrant / vagrant 로 접속 하시면 됩니다.

 

6. vagrant 삭제

vagrant destroy 로 vm 을 삭제 할수 있습니다.

$ vagrant destroy
    default: Are you sure you want to destroy the 'default' VM? [y/N] y
==> default: Forcing shutdown of VM...
==> default: Destroying VM and associated drives...