Skip to content

Instantly share code, notes, and snippets.

@ilwoong
Last active April 17, 2020 10:17
Show Gist options
  • Save ilwoong/58c8fe24b9a3b53388e1f6a1220617da to your computer and use it in GitHub Desktop.
Save ilwoong/58c8fe24b9a3b53388e1f6a1220617da to your computer and use it in GitHub Desktop.

Ubuntu에 Tensorflow를 Docker로 설치하기 (GPU사용)

윈도우에 VirtualBox 등의 가상환경에 우분투를 설치한 경우는 GPU를 사용할 수 없습니다. 꼭 가상환경에서 실행시켜야 한다면 GPU 설정 부분은 제외하고 CPU만 사용하는 도커 이미지를 사용하면 됩니다.

$ docker run -it -p 8888:8888 -v ~/workspace/notebooks:/tf tensorflow/tensorflow:latest-py3-jupyter

NVIDIA Driver 설치

우분투 설치 후 바로 그래픽 드라이버를 설치하면 오래전 드라이버를 설치하게 됩니다.

먼저 최신 드라이버를 받아올 ppa를 추가합니다.

$ sudo add-apt-repository ppa:grahpics-drivers/ppa

다음 명령어로 NVIDIA 그래픽 드라이버를 설치할 수 있습니다.

$ sudo ubuntu-drivers autoinstall

설치가 제대로 되었는지는 nvidia-smi 로 확인할 수 있습니다.

$ nvidia-smi
Sun Jun 30 09:47:57 2019
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 430.26       Driver Version: 430.26       CUDA Version: 10.2     |
|-------------------------------+----------------------+----------------------+
| 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  On |                  N/A |
| 29%   28C    P8    13W / 320W |    112MiB / 11175MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
|    0      1066      G   /usr/lib/xorg/Xorg                            39MiB |
|    0      1104      G   /usr/bin/gnome-shell                          70MiB |
+-----------------------------------------------------------------------------+

혹시 기존에 깔려있던 드라이버와 충돌이 나서 설치가 제대로 되지 않는다면 Ctrl + Alt + (F1 ~ F8) 을 눌러 CUI 콘솔모드로 전환하여 nvidia 관련 패키지를 모두 삭제하고 다시 위의 과정을 거치면 됩니다.

$ sudo apt-get remove --purge nvidia-*

참고

Docker CE 설치

혹시 오래된 Docker 버전이 설치되어 있으면 관련 패키지들을 삭제합니다.

$ sudo apt-get remove docker docker-engine docker.io containerd runc

필요한 패키지들을 다운받습니다.

$ sudo apt-get install apt-transport-https ca-certificates 
$ curl gnupg-agent software-properties-common

패키지 저정소를 위한 키를 다운받습니다.

$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

패키지 저장소 리스트를 추가하고 업데이트 합니다.

$ sudo add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
   $(lsb_release -cs) \
   stable"

$ sudo apt-get update

Docker CE를 설치합니다.

$ sudo apt-get install docker-ce docker-ce-cli containerd.io

제대로 설치되었는지 확인하기 위해 hello-world를 실행시켜봅니다.

$ sudo docker run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
1b930d010525: Pull complete
Digest: sha256:41a65640635299bab090f783209c1e3a3f11934cf7756b09cb2f1e02147c6ed8
Status: Downloaded newer image for hello-world:latest

Hello from Docker!
This message shows that your installation appears to be working correctly.

To generate this message, Docker took the following steps:
 1. The Docker client contacted the Docker daemon.
 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
    (amd64)
 3. The Docker daemon created a new container from that image which runs the
    executable that produces the output you are currently reading.
 4. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.

To try something more ambitious, you can run an Ubuntu container with:
 $ docker run -it ubuntu bash

Share images, automate workflows, and more with a free Docker ID:
 https://hub.docker.com/

For more examples and ideas, visit:
 https://docs.docker.com/get-started/

도커 실행시 sudo를 붙여야 하는 번거로움을 해결하기 위해 다음과 같이 현재 유저를 docker 그룹에 포함시킵니다.

$ sudo usermod -aG docker $USER

한번 로그아웃후 다시 로그인하면 그룹이 적용됩니다.

참고

NVIDIA-Docker 설치

패키지 저장소 리스트를 추가하고 업데이트 합니다.

$ curl -s -L https://nvidia.github.io/nvidia-docker/gpgkey | sudo apt-key add - 

$ distribution=$(. /etc/os-release;echo $ID$VERSION_ID)

$ curl -s -L https://nvidia.github.io/nvidia-docker/$distribution/nvidia-docker.list | sudo tee /etc/apt/sources.list.d/nvidia-docker.list

$ sudo apt-get update

Nvidia Docker를 설치하고, 도커 데몬을 재시작합니다.

$ sudo apt-get install -y nvidia-docker2
$ sudo pkill -SIGHUP dockerd

참고

Tensorflow Docker 설치

gpu, python3, jupyter notebook을 사용하는 tensorflow 도커 이미지는 다음과 같이 다운받을 수 있습니다.

$ docker pull tensorflow/tensorflow:latest-gpu-py3-jupyter

GPU를 제대로 활용할 수 있는지 확인하기 위해 다음을 실행해봅니다.

$ docker run --runtime=nvidia tensorflow/tensorflow:latest-gpu-py3-jupyter nvidia-smi
Sun Jun 30 01:45:17 2019
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 430.26       Driver Version: 430.26       CUDA Version: 10.2     |
|-------------------------------+----------------------+----------------------+
| 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  On |                  N/A |
| 29%   27C    P8    13W / 320W |    111MiB / 11175MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
+-----------------------------------------------------------------------------+

도커 이미지를 실행해봅니다.

$ docker run --runtime=nvidia -it -p 8888:8888 -v ~/workspace/notebooks:/tf tensorflow/tensorflow:latest-gpu-py3-jupyter
________                               _______________
___  __/__________________________________  ____/__  /________      __
__  /  _  _ \_  __ \_  ___/  __ \_  ___/_  /_   __  /_  __ \_ | /| / /
_  /   /  __/  / / /(__  )/ /_/ /  /   _  __/   _  / / /_/ /_ |/ |/ /
/_/    \___//_/ /_//____/ \____//_/    /_/      /_/  \____/____/|__/


WARNING: You are running this container as root, which can cause new files in
mounted volumes to be created as the root user on your host machine.

To avoid this, run the container by specifying your user's userid:

$ docker run -u $(id -u):$(id -g) args...

[I 01:25:02.387 NotebookApp] Writing notebook server cookie secret to /root/.local/share/jupyter/runtime/notebook_cookie_secret
jupyter_http_over_ws extension initialized. Listening on /http_over_websocket
[I 01:25:03.194 NotebookApp] Serving notebooks from local directory: /tf
[I 01:25:03.194 NotebookApp] The Jupyter Notebook is running at:
[I 01:25:03.194 NotebookApp] http://(e213b282a87a or 127.0.0.1):8888/?token=26bbd4f6b97e20f510d350c2680ef7795d83a52a2529c7f0
[I 01:25:03.194 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
[C 01:25:03.197 NotebookApp]

    To access the notebook, open this file in a browser:
        file:///root/.local/share/jupyter/runtime/nbserver-1-open.html
    Or copy and paste one of these URLs:
        http://(e213b282a87a or 127.0.0.1):8888/?token=26bbd4f6b97e20f510d350c2680ef7795d83a52a2529c7f0

실행시켰을 때 나오는 토큰값을 가지고 브라우저에서 Jupyter Notebook에 접속할 수 있습니다.

-v옵션 관련

기본적으로 도커 이미지는 휘발성이라 종료하면 데이터가 사라집니다. 데이터를 유지하기 위해 -v 옵션으로 호스트의 특정 폴더를 마운트할 수 있습니다.

현재 실행중인 도커 이미지의 아이디를 확인합니다.

$ docker ps
CONTAINER ID        IMAGE                                          COMMAND                  CREATED              STATUS              PORTS                                                                                                                                                                                                NAMES
e213b282a87a        tensorflow/tensorflow:latest-gpu-py3-jupyter   "bash -c 'source /et…"   About a minute ago   Up About a minute   0.0.0.0:8888                                                                                                                                                                            ->8888/tcp   nifty_lalande

어느 폴더에 마운트해야 할지 확인하기 위해 실행중인 도커 이미지의 shell을 실행시켜봅니다.

$ docker exec -it e213b282a87a /bin/bash
________                               _______________
___  __/__________________________________  ____/__  /________      __
__  /  _  _ \_  __ \_  ___/  __ \_  ___/_  /_   __  /_  __ \_ | /| / /
_  /   /  __/  / / /(__  )/ /_/ /  /   _  __/   _  / / /_/ /_ |/ |/ /
/_/    \___//_/ /_//____/ \____//_/    /_/      /_/  \____/____/|__/


WARNING: You are running this container as root, which can cause new files in
mounted volumes to be created as the root user on your host machine.

To avoid this, run the container by specifying your user's userid:

$ docker run -u $(id -u):$(id -g) args...

root@e213b282a87a:/tf## ls /
bin  boot  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tf  tmp  usr  var

제가 실행한 docker 이미지에서는 /tf 폴더에 노트북 데이터가 저장되게 되어 있습니다.

$ docker run [생략] -v ~/workspace/notebooks:/tf [생략]

이 옵션은 호스트의 ~/workspace/notebooks라는 폴더를 도커 이미지 안의 /tf 폴더로 마운트 한다는 뜻입니다.

참고

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment