최근 도커를 공부하다가 다른 컨테이너에 있는 프로세스끼리 어떤 식으로 통신하는지 궁금해져서 테스트를 해봤다. 

 
도커를 통해 두 개의 컨테이너를 만들 건데 하나는 nodejs 하나는 mongodb을 띄울 거다.


움 완성하고 보니 대충 이런 그림?


코드는 아래와 같이 진행하면 된다.


완성하고 보니 link로 연결하면 컨테이너의 /etc/hosts  에 다른 컨테이너 아이디가 등록된 것을 확인할 수 있었다.


도커프록시를 통해 내부에서 할당받은 아이피대역대끼리는 통신이 되기 때문에 이런 식으로 가능한 듯 ..


문득 궁금한게 k8s에서는 pod간 통신이 궁금해진.. ( 다음 포스팅에 올려볼예정 )


** 이 포스팅에 잘못 된 내용이 있으면 지적해주세요 


nodejs-mongo-test

First : mongodb을 시작한다. ( 여기선 docker를 이용하여 시작 ).


몽고디비 컨테이너에 생성

$ docker run --name mongo -p 27017:27017 -d mongo

도커 프로세스 확인

$ docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                      NAMES
b2482f6a58be        mongo               "docker-entrypoint.s…"   5 minutes ago       Up 5 minutes        0.0.0.0:27017->27017/tcp   mongo

컨테이너에 접속

$ docker exec -it mongo /bin/bash

mongo를 입력하여 제대로 동작하는지 확인

root@b2482f6a58be:/# mongo

MongoDB shell version v4.0.0
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 4.0.0
Server has startup warnings:
2018-06-30T04:51:49.681+0000 I STORAGE  [initandlisten]
2018-06-30T04:51:49.681+0000 I STORAGE  [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
2018-06-30T04:51:49.681+0000 I STORAGE  [initandlisten] **          See http://dochub.mongodb.org/core/prodnotes-filesystem
2018-06-30T04:51:50.154+0000 I CONTROL  [initandlisten]
2018-06-30T04:51:50.154+0000 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2018-06-30T04:51:50.154+0000 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2018-06-30T04:51:50.154+0000 I CONTROL  [initandlisten]
---
Enable MongoDB's free cloud-based monitoring service to collect and display
metrics about your deployment (disk utilization, CPU, operation statistics,
etc).

The monitoring data will be available on a MongoDB website with a unique
URL created for you. Anyone you share the URL with will also be able to
view this page. MongoDB may use this information to make product
improvements and to suggest MongoDB products and deployment options to you.

To enable free monitoring, run the following command:
db.enableFreeMonitoring()
>

>  db
test

Second : nodejs 실행


우선 해당 git에 프로젝트 다운

$ git clone https://github.com/yangjeehan/nodejs-mongo-test.git 

해당 도커파일을 통해 이미지를 만든다.

$ docker build -t nodejs-mongodb-test:yang

*만든 이미지를 실행한다. ( 전에 만든 mongo container을 link을 통해 연결 ) *

$ docker run -i --link mongo --name test -t nodejs-mongodb-test:yang /bin/bash 

만든 컨테이너에 접속하여 아래명령어 수행

$ docker exec -it test /bin/bash 
root@ee137a79dd4e:/usr/src/app# node demo_mongo_insert.js 

몽고디비에 접속해서 데이터 입력 체크

root@b2482f6a58be:/# mongo

> show databases;
admin   0.000GB
config  0.000GB
local   0.000GB
mydb    0.000GB

> use mydb
switched to db mydb
>
> show collections;
customers

> db.customers.find()
{ "_id" : ObjectId("5b371eb7d8daba00078e2fdf"), "name" : "Company Inc", "address" : "Highway 37" }

End


'apps > docker' 카테고리의 다른 글

도커란 무엇인가?  (0) 2018.08.04
flannel을 통한 pod간 통신  (2) 2018.07.03
kubernetes에서 gpu pod생성( nvidia-docker2 )  (2) 2018.05.30
centos7에서 nvidia driver설치하기  (0) 2018.05.28
kubenetes설치 실패 시 초기화방법  (0) 2018.05.28
Centos 7에서 설치를 진행하였습니다.

공식홈페이지에서 요구사항입니다.

Prerequisites

The list of prerequisites for running the NVIDIA device plugin is described below:

  • NVIDIA drivers ~= 361.93
  • nvidia-docker version > 2.0 (see how to install and it's prerequisites)
  • docker configured with nvidia as the default runtime.
  • Kubernetes version = 1.10
  • The DevicePlugins feature gate enabled


참고사이트 : 

먼저 nvidia-docker2 을 설치한다
이전에 버전1을 깔았다면 아래 명령어로 제거해준다.
$ yum install nvidia-docker2
docker volume ls -q -f driver=nvidia-docker | xargs -r -I{} -n1 docker ps -q -a -f volume={} | xargs -r docker rm -f
yum remove nvidia-docker


버전 2설치
$ yum install nvidia-docker2
$ pkill -SIGHUP dockerd


도커 실행

$ docker run --runtime=nvidia --rm nvidia/cuda nvidia-smi



도커에서 제대로 실행이 된다면 이젠 k8s에서 pod으로 띄워본다.


k8s에서 띄우기 위해선 몇가지 작업을 더 해줘야한다.


아래 과정들은 모든 노드에서 진행한다.

데몬 설정에 아래와 같이 해준다 path엔 실제 돌아가는 nvidia-container-runtime을 추가해준다.


$ vi /etc/docker/daemon.json
{
   "default-runtime": "nvidia",
    "runtimes": {
        "nvidia": {
            "path": "/usr/bin/nvidia-container-runtime-hook",
            "runtimeArgs": []
        }
    }
}

DevicePlugins에 아래와같이 하여 enable시켜준다
$ vi /etc/systemd/system/kubelet.service.d/10-kubeadm.conf
[Service]
Environment="KUBELET_KUBECONFIG_ARGS=--bootstrap-kubeconfig=/etc/kubernetes/bootstrap-kubelet.conf --kubeconfig=/etc/kubernetes/kubelet.conf"
Environment="KUBELET_SYSTEM_PODS_ARGS=--pod-manifest-path=/etc/kubernetes/manifests --allow-privileged=true"
Environment="KUBELET_NETWORK_ARGS=--network-plugin=cni --cni-conf-dir=/etc/cni/net.d --cni-bin-dir=/opt/cni/bin"
Environment="KUBELET_DNS_ARGS=--cluster-dns=10.96.0.10 --cluster-domain=cluster.local"
Environment="KUBELET_AUTHZ_ARGS=--authorization-mode=Webhook --client-ca-file=/etc/kubernetes/pki/ca.crt"
Environment="KUBELET_CADVISOR_ARGS=--cadvisor-port=0"
Environment="KUBELET_CGROUP_ARGS=--cgroup-driver=systemd"
Environment="KUBELET_CERTIFICATE_ARGS=--rotate-certificates=true --cert-dir=/var/lib/kubelet/pki"
Environment="KUBELET_EXTRA_ARGS=--feature-gates=DevicePlugins=true"

ExecStart=
ExecStart=/usr/bin/kubelet $KUBELET_KUBECONFIG_ARGS $KUBELET_SYSTEM_PODS_ARGS $KUBELET_NETWORK_ARGS $KUBELET_DNS_ARGS $KUBELET_AUTHZ_ARGS $KUBELET_CADVISOR_ARGS $KUBELET_CGROUP_ARGS $KUBELET_CERTIFICATE_ARGS $KUBELET_EXTRA_ARGS


데몬에 적용
$ systemctl daemon-reload
$ systemctl restart kubelet

쿠버네티스에 gpu support을 enable시켜준다. ( 버전 정보는 자신의 k8s 버전에 맞게 ^^ )

$ kubectl create -f https://raw.githubusercontent.com/NVIDIA/k8s-device-plugin/v1.10/nvidia-device-plugin.yml


pod이 제대로 떠있는지 확인 ( nvidia-device-plugin-daemonset 이 올라왔다면 완료 !) 

$ kubectl get pods --all-namespaces
NAMESPACE     NAME                                    READY     STATUS             RESTARTS   AGE
default       test-p-5f44f8586f-g98pd                 0/1       ImagePullBackOff   0          16m
kube-system   etcd-jframe-master                      1/1       Running            2          2d
kube-system   kube-apiserver-jframe-master            1/1       Running            2          2d
kube-system   kube-controller-manager-jframe-master   1/1       Running            2          2d
kube-system   kube-dns-86f4d74b45-nxqfr               3/3       Running            6          2d
kube-system   kube-flannel-ds-7dmtt                   1/1       Running            3          2d
kube-system   kube-flannel-ds-f9vbs                   1/1       Running            0          2d
kube-system   kube-proxy-9xgll                        1/1       Running            0          2d
kube-system   kube-proxy-w6hm8                        1/1       Running            3          2d
kube-system   kube-scheduler-jframe-master            1/1       Running            2          2d
kube-system   nvidia-device-plugin-daemonset-7vdwp    1/1       Running            6          2d

gpu의 개수를 출력해보았다 ( 실제론 master에도 gpu가 2개 장착되어있지만, 실제 pod가 실행되는 곳이 slave라 마스터엔 nvidia-device-plugin이 설치안된듯 )
만약 여기서 실제 노드에 gpu가 장착되어있음에도 0으로 잡힌다면 각 노드에서 docker ps을 통해 nvidia-device-plugin이 제대로 떠 있는지 확인해본다.
$ kubectl get nodes "-o=custom-columns=NAME:.metadata.name,GPU:.status.allocatable.nvidia\.com/gpu"
NAME             GPU
master    0
slave   2


만들어둔 yaml을 통해 실행시켜봤다.

$ cat test.yaml
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: gpu-demo
spec:
  replicas: 1
  template:
    metadata:
      labels:
        run: gpu-demo
      annotations:
        scheduler.alpha.kubernetes.io/nvidiaGPU: "{ \n  \"AllocationPriority\": \"Dense\"\n}\n"
    spec:
      containers:
      - name: gpu-demo
        image: nvidia/cuda:7.5-runtime
        command:
        - "/bin/sh"
        - "-c"
        args:
        - nvidia-smi && tail -f /dev/null
        resources:
          limits:
            alpha.kubernetes.io/gpu: 2

만들어둔 yaml을 통해 실행시켜봤다.

$ kubectl apply -f test.yaml

실행한 pod의 로그를 확인 ( 제대로 설치 된것을 확인할 수 있다 )
$ kubectl logs gpu-demo-85bdc64dd7-5grcg
Mon May 28 17:25:27 2018
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 390.59                 Driver Version: 390.59                    |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GTX 108...  Off  | 00000000:01:00.0 Off |                  N/A |
|  0%   48C    P8    18W / 250W |      0MiB / 11176MiB |      1%      Default |
+-------------------------------+----------------------+----------------------+
|   1  GeForce GTX 108...  Off  | 00000000:04:00.0 Off |                  N/A |
|  0%   41C    P8     9W / 250W |      0MiB / 11178MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
|  No running processes found                                                 |
+-----------------------------------------------------------------------------+


k8s에서 gpu을 사용하는 pod을 만들일이 있어 관련 내용을 정리하였다. 


gpu을 사용하기 위해서는 nvidia driver가 있어야한다.

  

이번 포스팅엔 먼저 nvidia 드라이버 설치 관련 내용을 정리하였다.


nvdia driver설치하기 

$ yum update
$ yum install kernel-devel kernel-headers gcc make
 

nouveau 을 활성화시키면 충돌가능성이 있기에 blacklist해준다. 
$ echo 'blacklist nouveau' >> /etc/modprobe.d/blacklist.conf
$ dracut /boot/initramfs-$(uname -r).img $(uname -r) --force
$ reboot

파일다운

이것저것 뜨는데 다 ok, yes해줌 된다.
$ bash NVIDIA-Linux-x86_64-390.59.run

1. WARNING: nvidia-installer was forced to guess the X library path '/usr/lib64' and X
           module path '/usr/lib64/xorg/modules'; these paths were not queryable from the
           system.  If X fails to find the NVIDIA X driver module, please install the
           `pkg-config` utility and the X.Org SDK/development package for your distribution
           and reinstall the driver
OK
2. Install NVIDIA's 32-bit compatibility libraries?
YES

3. Would you like to run the nvidia-xconfig utility to automatically update your X
  configuration file so that the NVIDIA X driver will be used when you restart X?  Any
  pre-existing X configuration file will be backed up.
YES

4.  Your X configuration file has been successfully updated.  Installation of the NVIDIA
  Accelerated Graphics Driver for Linux-x86_64 (version: 390.59) is now complete.
OK



$ nvidia-smi


Thu May 24 21:39:10 2018
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 390.59                 Driver Version: 390.59                    |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GTX 108...  Off  | 00000000:01:00.0 Off |                  N/A |
|  0%   34C    P5    15W / 250W |      0MiB / 11178MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+
|   1  GeForce GTX 108...  Off  | 00000000:04:00.0 Off |                  N/A |
|  0%   33C    P5    13W / 250W |      0MiB / 11178MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
|  No running processes found                                                 | 


위 화면이 뜬다면 완료 

+ Recent posts