본문 바로가기
  • 경제적 자유를 얻는 그날까지
엔지니어링/프로그래밍

Docker의 개념, 설치 및 사용방법

by 베니스상인 2021. 8. 21.

1. Docker 의 개념

Image

  • 환경을 구성하기 위한 Instruction이 들어가 있는 저장소

 

Container

  • Image의 Instruction을 이용하여 만들어진 환경
  • 하나의 Image를 이용하여 여러 종류의 Container를 만들어낼 수 있음

 

 

2. Docker 설치하기

 

기존의 Docker 가 설치되어 있는지 확인후 설치를 진행

swift@swift-HP-Pavilion-dv6-Notebook-PC:~/workspace/project/ros/catkin_ws/src$ sudo apt-get remove docker docker-engine docker.io containerd runc
[sudo] password for swift: 
Reading package lists... Done
Building dependency tree       
Reading state information... Done
E: Unable to locate package docker-engine


swift@swift-HP-Pavilion-dv6-Notebook-PC:~/workspace/project/ros/catkin_ws/src$ sudo apt-get update
Hit:1 http://kr.archive.ubuntu.com/ubuntu focal InRelease                                                                                             
Hit:2 http://packages.ros.org/ros/ubuntu focal InRelease                                                                                              
Hit:3 http://security.ubuntu.com/ubuntu focal-security InRelease
Hit:4 http://kr.archive.ubuntu.com/ubuntu focal-updates InRelease
Hit:5 http://kr.archive.ubuntu.com/ubuntu focal-backports InRelease
Reading package lists... Done


swift@swift-HP-Pavilion-dv6-Notebook-PC:~/workspace/project/ros/catkin_ws/src$ sudo apt-get install apt-transport-https ca-certificates curl gnupg lsb-release
Reading package lists... Done
Building dependency tree       
Reading state information... Done
lsb-release is already the newest version (11.1.0ubuntu2).
lsb-release set to manually installed.
ca-certificates is already the newest version (20210119~20.04.1).
ca-certificates set to manually installed.
curl is already the newest version (7.68.0-1ubuntu2.6).
gnupg is already the newest version (2.2.19-3ubuntu2.1).
gnupg set to manually installed.
The following packages were automatically installed and are no longer required:
  libllvm11 libmbim-glib4 libmbim-proxy libqmi-glib5 libqmi-proxy usb-modeswitch usb-modeswitch-data
Use 'sudo apt autoremove' to remove them.
The following NEW packages will be installed:
  apt-transport-https
0 upgraded, 1 newly installed, 0 to remove and 29 not upgraded.
Need to get 4,680 B of archives.
After this operation, 162 kB of additional disk space will be used.
Do you want to continue? [Y/n] Y
Get:1 http://kr.archive.ubuntu.com/ubuntu focal-updates/universe amd64 apt-transport-https all 2.0.6 [4,680 B]
Fetched 4,680 B in 1s (5,679 B/s)                       
Selecting previously unselected package apt-transport-https.
(Reading database ... 295553 files and directories currently installed.)
Preparing to unpack .../apt-transport-https_2.0.6_all.deb ...
Unpacking apt-transport-https (2.0.6) ...
Setting up apt-transport-https (2.0.6) ...


swift@swift-HP-Pavilion-dv6-Notebook-PC:~/workspace/project/ros/catkin_ws/src$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg

swift@swift-HP-Pavilion-dv6-Notebook-PC:~/workspace/project/ros/catkin_ws/src$ echo \
  "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu \
  $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

swift@swift-HP-Pavilion-dv6-Notebook-PC:~/workspace/project/ros/catkin_ws/src$ sudo apt-get update

swift@swift-HP-Pavilion-dv6-Notebook-PC:~/workspace/project/ros/catkin_ws/src$ sudo apt-get install docker-ce docker-ce-cli containerd.io
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following packages were automatically installed and are no longer required:
  libllvm11 libmbim-glib4 libmbim-proxy libqmi-glib5 libqmi-proxy usb-modeswitch usb-modeswitch-data
Use 'sudo apt autoremove' to remove them.
The following additional packages will be installed:
  docker-ce-rootless-extras docker-scan-plugin pigz slirp4netns
Suggested packages:
  aufs-tools cgroupfs-mount | cgroup-lite
The following NEW packages will be installed:
  containerd.io docker-ce docker-ce-cli docker-ce-rootless-extras docker-scan-plugin pigz slirp4netns
0 upgraded, 7 newly installed, 0 to remove and 29 not upgraded.
Need to get 96.7 MB of archives.
After this operation, 406 MB of additional disk space will be used.
Do you want to continue? [Y/n] Y
Get:1 https://download.docker.com/linux/ubuntu focal/stable amd64 containerd.io amd64 1.4.9-1 [24.7 MB]
Get:2 http://kr.archive.ubuntu.com/ubuntu focal/universe amd64 pigz amd64 2.4-1 [57.4 kB]    
Get:3 http://kr.archive.ubuntu.com/ubuntu focal/universe amd64 slirp4netns amd64 0.4.3-1 [74.3 kB]
Get:4 https://download.docker.com/linux/ubuntu focal/stable amd64 docker-ce-cli amd64 5:20.10.8~3-0~ubuntu-focal [38.8 MB]
Get:5 https://download.docker.com/linux/ubuntu focal/stable amd64 docker-ce amd64 5:20.10.8~3-0~ubuntu-focal [21.2 MB]                                
Get:6 https://download.docker.com/linux/ubuntu focal/stable amd64 docker-ce-rootless-extras amd64 5:20.10.8~3-0~ubuntu-focal [7,917 kB]               
Get:7 https://download.docker.com/linux/ubuntu focal/stable amd64 docker-scan-plugin amd64 0.8.0~ubuntu-focal [3,889 kB]                              
Fetched 96.7 MB in 16s (5,896 kB/s)                                                                                                                   
Selecting previously unselected package pigz.
(Reading database ... 295557 files and directories currently installed.)
Preparing to unpack .../0-pigz_2.4-1_amd64.deb ...
Unpacking pigz (2.4-1) ...
Selecting previously unselected package containerd.io.
Preparing to unpack .../1-containerd.io_1.4.9-1_amd64.deb ...
Unpacking containerd.io (1.4.9-1) ...
Selecting previously unselected package docker-ce-cli.
Preparing to unpack .../2-docker-ce-cli_5%3a20.10.8~3-0~ubuntu-focal_amd64.deb ...
Unpacking docker-ce-cli (5:20.10.8~3-0~ubuntu-focal) ...
Selecting previously unselected package docker-ce.
Preparing to unpack .../3-docker-ce_5%3a20.10.8~3-0~ubuntu-focal_amd64.deb ...
Unpacking docker-ce (5:20.10.8~3-0~ubuntu-focal) ...
Selecting previously unselected package docker-ce-rootless-extras.
Preparing to unpack .../4-docker-ce-rootless-extras_5%3a20.10.8~3-0~ubuntu-focal_amd64.deb ...
Unpacking docker-ce-rootless-extras (5:20.10.8~3-0~ubuntu-focal) ...
Selecting previously unselected package docker-scan-plugin.
Preparing to unpack .../5-docker-scan-plugin_0.8.0~ubuntu-focal_amd64.deb ...
Unpacking docker-scan-plugin (0.8.0~ubuntu-focal) ...
Selecting previously unselected package slirp4netns.
Preparing to unpack .../6-slirp4netns_0.4.3-1_amd64.deb ...
Unpacking slirp4netns (0.4.3-1) ...
Setting up slirp4netns (0.4.3-1) ...
Setting up docker-scan-plugin (0.8.0~ubuntu-focal) ...
Setting up containerd.io (1.4.9-1) ...
Created symlink /etc/systemd/system/multi-user.target.wants/containerd.service → /lib/systemd/system/containerd.service.
Setting up docker-ce-cli (5:20.10.8~3-0~ubuntu-focal) ...
Setting up pigz (2.4-1) ...
Setting up docker-ce-rootless-extras (5:20.10.8~3-0~ubuntu-focal) ...
Setting up docker-ce (5:20.10.8~3-0~ubuntu-focal) ...
Created symlink /etc/systemd/system/multi-user.target.wants/docker.service → /lib/systemd/system/docker.service.
Created symlink /etc/systemd/system/sockets.target.wants/docker.socket → /lib/systemd/system/docker.socket.
Processing triggers for man-db (2.9.1-1) ...
Processing triggers for systemd (245.4-4ubuntu3.11) ...

 

 

참고자료

https://docs.docker.com/engine/install/ubuntu/

 

Install Docker Engine on Ubuntu

 

docs.docker.com

 

 

 

 

 

Docker 설치결과 확인

swift@swift-HP-Pavilion-dv6-Notebook-PC:~/workspace/project/ros/catkin_ws/src$ apt-cache madison docker-ce
 docker-ce | 5:20.10.8~3-0~ubuntu-focal | https://download.docker.com/linux/ubuntu focal/stable amd64 Packages
 docker-ce | 5:20.10.7~3-0~ubuntu-focal | https://download.docker.com/linux/ubuntu focal/stable amd64 Packages
 docker-ce | 5:20.10.6~3-0~ubuntu-focal | https://download.docker.com/linux/ubuntu focal/stable amd64 Packages
 docker-ce | 5:20.10.5~3-0~ubuntu-focal | https://download.docker.com/linux/ubuntu focal/stable amd64 Packages
 docker-ce | 5:20.10.4~3-0~ubuntu-focal | https://download.docker.com/linux/ubuntu focal/stable amd64 Packages
 docker-ce | 5:20.10.3~3-0~ubuntu-focal | https://download.docker.com/linux/ubuntu focal/stable amd64 Packages
 docker-ce | 5:20.10.2~3-0~ubuntu-focal | https://download.docker.com/linux/ubuntu focal/stable amd64 Packages
 docker-ce | 5:20.10.1~3-0~ubuntu-focal | https://download.docker.com/linux/ubuntu focal/stable amd64 Packages
 docker-ce | 5:20.10.0~3-0~ubuntu-focal | https://download.docker.com/linux/ubuntu focal/stable amd64 Packages
 docker-ce | 5:19.03.15~3-0~ubuntu-focal | https://download.docker.com/linux/ubuntu focal/stable amd64 Packages
 docker-ce | 5:19.03.14~3-0~ubuntu-focal | https://download.docker.com/linux/ubuntu focal/stable amd64 Packages
 docker-ce | 5:19.03.13~3-0~ubuntu-focal | https://download.docker.com/linux/ubuntu focal/stable amd64 Packages
 docker-ce | 5:19.03.12~3-0~ubuntu-focal | https://download.docker.com/linux/ubuntu focal/stable amd64 Packages
 docker-ce | 5:19.03.11~3-0~ubuntu-focal | https://download.docker.com/linux/ubuntu focal/stable amd64 Packages
 docker-ce | 5:19.03.10~3-0~ubuntu-focal | https://download.docker.com/linux/ubuntu focal/stable amd64 Packages
 docker-ce | 5:19.03.9~3-0~ubuntu-focal | https://download.docker.com/linux/ubuntu focal/stable amd64 Packages




swift@swift-HP-Pavilion-dv6-Notebook-PC:~$ sudo docker run hello-world

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/

swift@swift-HP-Pavilion-dv6-Notebook-PC:~$

 

 

 

 

 

 

스크립트로 설치하는 방법

swift@swift-HP-Pavilion-dv6-Notebook-PC:~/workspace/project/ros/catkin_ws/src/PX4-Autopilot$ curl -fsSL get.docker.com -o get-docker.sh
swift@swift-HP-Pavilion-dv6-Notebook-PC:~/workspace/project/ros/catkin_ws/src/PX4-Autopilot$ sudo sh get-docker.sh
[sudo] password for swift: 
# Executing docker install script, commit: 93d2499759296ac1f9c510605fef85052a2c32be
Warning: the "docker" command appears to already exist on this system.

If you already have Docker installed, this script can cause trouble, which is
why we're displaying this warning and provide the opportunity to cancel the
installation.

If you installed the current Docker package using this script and are using it
again to update Docker, you can safely ignore this message.

You may press Ctrl+C now to abort this script.
+ sleep 20
+ sh -c apt-get update -qq >/dev/null
+ sh -c DEBIAN_FRONTEND=noninteractive apt-get install -y -qq apt-transport-https ca-certificates curl >/dev/null
+ sh -c curl -fsSL "https://download.docker.com/linux/ubuntu/gpg" | gpg --dearmor --yes -o /usr/share/keyrings/docker-archive-keyring.gpg
+ sh -c echo "deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu focal stable" > /etc/apt/sources.list.d/docker.list
+ sh -c apt-get update -qq >/dev/null
+ sh -c DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends  docker-ce-cli docker-scan-plugin docker-ce >/dev/null
+ version_gte 20.10
+ [ -z  ]
+ return 0
+ sh -c DEBIAN_FRONTEND=noninteractive apt-get install -y -qq docker-ce-rootless-extras >/dev/null
+ sh -c docker version
Client: Docker Engine - Community
 Version:           20.10.8
 API version:       1.41
 Go version:        go1.16.6
 Git commit:        3967b7d
 Built:             Fri Jul 30 19:54:27 2021
 OS/Arch:           linux/amd64
 Context:           default
 Experimental:      true

Server: Docker Engine - Community
 Engine:
  Version:          20.10.8
  API version:      1.41 (minimum version 1.12)
  Go version:       go1.16.6
  Git commit:       75249d8
  Built:            Fri Jul 30 19:52:33 2021
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          1.4.9
  GitCommit:        e25210fe30a0a703442421b0f60afac609f950a3
 runc:
  Version:          1.0.1
  GitCommit:        v1.0.1-0-g4144b63
 docker-init:
  Version:          0.19.0
  GitCommit:        de40ad0

================================================================================

To run Docker as a non-privileged user, consider setting up the
Docker daemon in rootless mode for your user:

    dockerd-rootless-setuptool.sh install

Visit https://docs.docker.com/go/rootless/ to learn about rootless mode.


To run the Docker daemon as a fully privileged service, but granting non-root
users access, refer to https://docs.docker.com/go/daemon-access/

WARNING: Access to the remote API on a privileged Docker daemon is equivalent
         to root access on the host. Refer to the 'Docker daemon attack surface'
         documentation for details: https://docs.docker.com/go/attack-surface/

================================================================================

swift@swift-HP-Pavilion-dv6-Notebook-PC:~/workspace/project/ros/catkin_ws/src/PX4-Autopilot$ 











swift@swift-HP-Pavilion-dv6-Notebook-PC:~$ sudo docker run hello-world

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/

swift@swift-HP-Pavilion-dv6-Notebook-PC:~$

 

 

 

 

 

 

Docker 계정을 사용자 계정에 추가

$ sudo groupadd docker

$ sudo usermod -aG docker $USER

$ newgrp docker

 

 

3. Docker 활용하기

 

 

도커 이미지 실행

  • 최초 실행시 이미지를 docker hub에서 다운받아와서 실행한다. 
  • 아래 예제는  ubuntu 이미지를 다운받아왔으며 latest는 최신버전을 의미한다.
swift@swift-HP-Pavilion-dv6-Notebook-PC:~$ sudo docker run -dit ubuntu:latest
Unable to find image 'ubuntu:latest' locally
latest: Pulling from library/ubuntu
16ec32c2132b: Pull complete 
Digest: sha256:82becede498899ec668628e7cb0ad87b6e1c371cb8a1e597d83a47fac21d6af3
Status: Downloaded newer image for ubuntu:latest
454393d7c2efe4021346aa2c90b9404cea7b35e5c3db3c300aa5e0b5f04e3d16

 

이미지 확인

  • 도커 이미지 리스트를 확인할 수 있다
swift@swift-HP-Pavilion-dv6-Notebook-PC:~$ sudo docker images
REPOSITORY                  TAG          IMAGE ID       CREATED        SIZE
ubuntu                      latest       1318b700e415   3 weeks ago    72.8MB
px4io/px4-dev-nuttx-focal   2021-05-04   fd42e200082d   3 months ago   2.69GB
hello-world                 latest       d1165f221234   5 months ago   13.3kB

 

 

 

컨테이너 상태 확인

  • 현재 컨테이너의 상태를 확인할 수 있다. 
  • Up은 실행중인 상태이며 Exited는 exit 명령어를 통하여 중단된 상태이다. 다시 시작하려면 docker start [ CONTAINER ID or NAMES ]를 해줘야 한다.
swift@swift-HP-Pavilion-dv6-Notebook-PC:~$ sudo docker ps -a
[sudo] password for swift: 
CONTAINER ID   IMAGE           COMMAND    CREATED        STATUS                    PORTS     NAMES
454393d7c2ef   ubuntu:latest   "bash"     3 hours ago    Up 3 hours                          happy_robinson
9a3b9a141ee8   hello-world     "/hello"   3 hours ago    Exited (0) 3 hours ago              suspicious_merkle
017c905df2d9   hello-world     "/hello"   3 hours ago    Exited (0) 3 hours ago              laughing_maxwell
2c783bb772d3   hello-world     "/hello"   4 hours ago    Exited (0) 4 hours ago              vibrant_bose
fcc3c7cab75b   hello-world     "/hello"   13 hours ago   Exited (0) 13 hours ago             peaceful_torvalds

 

 

실행중인 컨테이너로 다시 접속하기

  • 실행중인 컨테이너에서 나왔다가 다시 돌아갈 때 아래와 같이 실행하면 된다.
swift@swift-HP-Pavilion-dv6-Notebook-PC:~$ sudo docker attach happy_robinson 
root@454393d7c2ef:/# 
root@454393d7c2ef:/# 
root@454393d7c2ef:/# 
root@454393d7c2ef:/# ls
bin   dev  home  lib32  libx32  mnt  proc  run   srv  tmp  var
boot  etc  lib   lib64  media   opt  root  sbin  sys  usr

 

 

새로운 터미널로 접속하기 

  • 새로운 터미널을 열어 현재 실행중인 컨테이너로 접속하려면 아래와 같이 실행할 수 있다.
docker exec -it <CONTAINER_NAME> bash

 

 

컨테이너 삭제 명령

swift@swift-HP-Pavilion-dv6-Notebook-PC:~$ sudo docker rm suspicious_merkle 
suspicious_merkle


swift@swift-HP-Pavilion-dv6-Notebook-PC:~$ sudo docker ps -a
CONTAINER ID   IMAGE           COMMAND   CREATED       STATUS       PORTS     NAMES
454393d7c2ef   ubuntu:latest   "bash"    3 hours ago   Up 3 hours             happy_robinson

 

 

이미지 삭제 명령

swift@swift-HP-Pavilion-dv6-Notebook-PC:~$ sudo docker images
REPOSITORY                  TAG          IMAGE ID       CREATED        SIZE
ubuntu                      latest       1318b700e415   3 weeks ago    72.8MB
px4io/px4-dev-nuttx-focal   2021-05-04   fd42e200082d   3 months ago   2.69GB


swift@swift-HP-Pavilion-dv6-Notebook-PC:~$ sudo docker rmi px4io/px4-dev-nuttx-focal:2021-05-04 
Untagged: px4io/px4-dev-nuttx-focal:2021-05-04
Untagged: px4io/px4-dev-nuttx-focal@sha256:d4cbc55f6743ff3464de22e0baf6ff7431aff740544f68c886700c46a77c234c
Deleted: sha256:fd42e200082df152a72773978f5fb066db605449ada99f89898e8716a3f2235f
Deleted: sha256:2882924f334ea71753c016306c205d33bc6d4ed6883761e8e523d9333e6c5bfc
Deleted: sha256:60899bbf2355169d761b5a755dad91807df2a20a596bc82f45b2fd12f0ad4867
Deleted: sha256:8fff0aeab65cfe9e95e28f157bd2d52b2cf2661ff6df2acf88d011c3666979d0
Deleted: sha256:c7a4ffe0ac8c71a3251b069abb7e0723182e29447ce09d8ec43176b9b673340d
Deleted: sha256:6ff931243dfb0444e9842ad26abdd7e5f7425d1df1f412ba4535710793336f78
Deleted: sha256:c4311f942eed6d6f83a2db6425b7f058047efb755d589861d68cd82d2da49235
Deleted: sha256:2eb70cccea5433ca7909f902f8789d4450b4f08fd8376b231bb3d257941c972c
Deleted: sha256:bf2dcac549cef16ed5fee2f6b53423df02715b87d5865bb617854910648f8b70
Deleted: sha256:dea0a46d061b250e751a0bda2d2f5d9f12958798c1d825f0e6d1d59bdf56c415
Deleted: sha256:ebf6be42719a4c4f32d614b534394c44ccefc7922758e3e1cdbc6bfb725fd627
Deleted: sha256:29ef37171ea2a45fe61727b361e3e7894fcea7aea5c19b093c2b87a8e52a88d6
Deleted: sha256:a389957d9572a322b1cc4572b967acd23ee175457717e2dca9b114be606f9729
Deleted: sha256:f74bfbf54c8ef9438dc722df0e774da057d0da048ee61ea960de5d7542460a12
Deleted: sha256:7a147572e9449b9b561f02fd5782daa7ee3184ab6aa8ea1b38b1cd65ca62dd25
Deleted: sha256:9453f0a685427ae6f60d8304d6de24f2c1455ff11c2163007bdfbca0fffcbe8e
Deleted: sha256:4ab3c3bb267ae0525e96ad3b1369f223f4dc0c0bddb124986e656ba39ff21345
Deleted: sha256:4d9ee713ba7deff926470ad29685aca94ad1e7aacfd4108d900c52d0d282ec5f
Deleted: sha256:ddf19f4fc5db1a7ec6ed74f61c9da199e1987df59dcb1b40066a90b7a69e5f6f
Deleted: sha256:3dd8c8d4fd5b59d543c8f75a67cdfaab30aef5a6d99aea3fe74d8cc69d4e7bf2
Deleted: sha256:8d8dceacec7085abcab1f93ac1128765bc6cf0caac334c821e01546bd96eb741
Deleted: sha256:ccdbb80308cc5ef43b605ac28fac29c6a597f89f5a169bbedbb8dec29c987439


swift@swift-HP-Pavilion-dv6-Notebook-PC:~$ sudo docker images
REPOSITORY   TAG       IMAGE ID       CREATED       SIZE
ubuntu       latest    1318b700e415   3 weeks ago   72.8MB

 

 

 

 

Docker run 명령어(run-docker.sh)

  • -it 터미널을 통한 인터렉티브 상태로 실행
  • -v 폴더를 공유하여 docker에서 사용 가능
#!/bin/bash
#set -x

# sudo usermod -aG docker $USER
# newgrp docker

USER_UID=$(id -u)
TAG='ros-melodic-dev'
IMAGE='osrf/ros:melodic-desktop-full'
TTY='--device=/dev/ttyACM0'


xhost +$(hostname -I | cut -d' ' -f1)

echo "IMAGE=" $IMAGE
echo "TAG=" $TAG
echo "USER_UID=" $USER_UID
echo "USER=" $USER
echo "IPADDR=" $(hostname -I | cut -d' ' -f1)
echo "TTY=" $TTY


ENV_PARAMS=()
OTHER_PARAMS=()
args=("$@")
for ((a=0; a<"${#args[@]}"; ++a)); do
    case ${args[a]} in
        #-e) ENV_PARAMS+=("${args[a+1]}"); unset args[a+1]; ;;
        -e) ENV_PARAMS+=("${args[a]} ${args[a+1]}"); ((++a)); ;;
        --env=*) ENV_PARAMS+=("${args[a]}"); ;;
        *) OTHER_PARAMS+=("${args[a]}"); ;;
    esac
done


docker run -it \
    --init \
    -e DISPLAY=$DISPLAY \
    -e QT_GRAPHICSSYSTEM=native \
    -e CONTAINER_NAME=$TAG \
    -e USER=$USER \
    --env=UDEV=1 \
    --env=LIBUSB_DEBUG=1 \
    --env="DISPLAY" \
    --env="QT_X11_NO_MITSHM=1" \
    ${ENV_PARAMS[@]} \
    --volume="/tmp/.X11-unix:/tmp/.X11-unix:rw" \
    --volume="/home/$USER/workspace:/root/workspace" \
    --name=$TAG \
    $IMAGE \
    ${OTHER_PARAMS[@]}    
export containerId=$(docker ps -l -q)

 

 

docker 실행이후 컨테이너 안에서 필요한 초기 설정(init.sh)

  • 공유폴더에 넣어주고, docker 생성이후 실행하면 됨
#!/bin/bash


cat /etc/apt/sources.list
apt-get autoremove --purge --yes \
    && rm -rf /var/lib/apt/lists/* \
    && rm -rf /etc/ros/rosdep/sources.list.d/20-default.list
sed -i -e 's+\(^deb http://security.*\)+# \1+g' /etc/apt/sources.list
apt-get clean && apt-get update 


apt-get install -y \
    tmux \
    curl \
    wget \
    vim \
    git \
    sudo \
    libgl1-mesa-glx \
    libgl1-mesa-dri \
    mesa-utils \
    unzip \
    locales \
    ntp \
    whois \
    sudo \
    net-tools \
    ssh

locale-gen en_US.UTF-8
LANG en_US.UTF-8  
LANGUAGE en_US:en  
LC_ALL en_US.UTF-8  

rosdep init
rosdep update 
rosdep fix-permissions 

sudo apt-get install python-rosinstall -y   \
    ros-melodic-rqt*

echo HOME=${HOME}


# 빌드 패키지 설치
apt-get -y install \ 
    build-essential \
    sudo \
    python3 \
    python3-pip \
    python-rosinstall \
    python-rosinstall-generator \
    python-wstool
apt-get autoclean



# 3
mkdir -p $HOME/workspace/catkin_ws/src && cd $HOME/workspace/catkin_ws/src && catkin_init_workspace

# 소스코드 다운로드

cd $HOME/workspace/catkin_ws && catkin_make

echo "source /opt/ros/melodic/setup.bash" >> $HOME/.bashrc
echo "source /$HOME/workspace/catkin_ws/devel/setup.bash" >> $HOME/.bashrc
echo "export ROS_HOSTNAME=localhost" >> $HOME/.bashrc
echo "export ROS_MASTER_URI=http://localhost:11311" >> $HOME/.bashrc
echo "alias cw='cd ~/workspace/catkin_ws'" >> $HOME/.bashrc
echo "alias cs='cd ~/workspace/catkin_ws/src'" >> $HOME/.bashrc
echo "alias cm='cd ~/workspace/catkin_ws && catkin_make'" >> $HOME/.bashrc

source /opt/ros/$ROS_DISTRO/setup.bash
source /$HOME/workspace/catkin_ws/devel/setup.bash

IPADDR=$(hostname -I | cut -d' ' -f1)
echo "USER=$USER"
echo "HOME=$HOME"
echo "IPADDR=$IPADDR"
echo "ROS_ROOT=$ROS_ROOT"
echo "ROS_PACKAGE_PATH=$ROS_PACKAGE_PATH"
echo "ROS_HOSTNAME=$ROS_HOSTNAME"
echo "ROS_MASTER_URI=$ROS_MASTER_URI"

 

 

Docker  셀 명령어로 실행하기

  • 엔트리포인트를 지나고 나면 $Home은 root폴더가 되므로 아래와 같이 실행하면 된다.
swift@swift-MacBookPro:~/workspace$ ./run-docker.sh ./root/workspace/init.sh

 

 

 

 

 

 

Docker build 사용하기

  • .Dockerfile 은 clean ubuntu에 본인에게 맞는 Configuration과 설정을 파일에 기록하여 빌드할 수 있음
sudo docker build --no-cache --force-rm -f ros_melodic_base.dockerfile --build-arg HOST_USER=$USER -t ros/melodic:base .
  •  --no-cache 는 이전 빌드에서 생성된 캐시를 사용하지 않음
  •  --force-rm 은 빌드하다가 fail시 자동 삭제
  •  -f 는 사용할 Dockerfile의 이름을 명시
  •  -t 는 우리가 만드는 이미지의 이름 + 태그를 명시
  •  . 는 Dockerfile의 경로를 명시

 

 

 

 

dockerfile 작성

  • ubuntu + ROS + 빌드 패키지 + GUI 환경
# docker hub에서 받아올 base image
FROM osrf/ros:kinetic-desktop-full

# 작성자
MAINTAINER shlee853




# apt로 패키지 받을 때 interative하게 사용하는 기능들을 끕니다. Docker에서 로그를 넘길 때 문제가 생길 수 있으므로 이 옵션은 필수입니다!
ARG DEBIAN_FRONTEND=noninteractive




# clean up first
RUN apt-get autoremove --purge --yes \
    && rm -rf /var/lib/apt/lists/* \
    && rm -rf /etc/ros/rosdep/sources.list.d/20-default.list



# 필수 유틸리티 설치
RUN apt-get update && apt-get install -y \
    tmux \
    curl \
    wget \
    vim \
    git \
    sudo \
    libgl1-mesa-glx \
    libgl1-mesa-dri \
    mesa-utils \
    unzip \
    locales \
    ntp \
    whois \
    net-tools \
    sudo



RUN locale-gen en_US.UTF-8
ENV LANG en_US.UTF-8  
ENV LANGUAGE en_US:en  
ENV LC_ALL en_US.UTF-8  





# rosdep는 ROOT권한으로 실행하는걸 권장하지 않는다
# HOST_USER from build arguemnt
ARG HOST_USER
ARG UNAME=${HOST_USER}
ARG UID=1000
ARG GID=1000
ARG HOME=/home/${UNAME}
RUN useradd -rm -d ${HOME} -s /bin/bash -g root -G sudo,audio,video,plugdev -u ${UID} ${UNAME}
RUN mkdir -p /etc/sudoers.d && \
    echo "${UNAME} ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/${UNAME} && \
    chmod 0440 /etc/sudoers.d/${UNAME} 

USER ${UNAME}
WORKDIR $HOME


# ROS packages 설치
RUN rosdep init
RUN sudo rosdep fix-permissions 
RUN rosdep update 


# 빌드 패키지 설치
RUN apt-get -y install build-essential sudo &&\
apt-get -y install python3 python3-pip &&\
apt-get -y install python-rosinstall python-rosinstall-generator python-wstool &&\
apt-get autoclean




ADD initial-workspace.sh $HOME/

# node들을 실행할때 필요한 환경변수들은 미리 초기화 한다.
RUN echo "source /opt/ros/kinetic/setup.bash" >> $HOME/.bashrc
RUN echo "source \$HOME/docker_share/catkin_ws/devel/setup.bash" >> $HOME/.bashrc
RUN echo "export ROS_HOSTNAME=localhost" >> $HOME/.bashrc
RUN echo "export ROS_MASTER_URI=http://localhost:11311" >> $HOME/.bashrc
RUN echo "alias cw='cd ~/docker_share/catkin_ws'" >> $HOME/.bashrc
RUN echo "alias cs='cd ~/docker_share/catkin_ws/src'" >> $HOME/.bashrc
RUN echo "alias cm='cd ~/docker_share/catkin_ws && catkin_make'" >> $HOME/.bashrc

ADD ros_entrypoint2.sh /










# ROS 패키지 설치
RUN apt-get -y update &&\
apt-get -y install build-essential cmake git sudo wget &&\
apt-get -y install python3 python3-pip &&\
apt-get autoclean




# 원하는 프로젝트의 소스코드를 clone해와서 빌드 스크립트를 실행합니다
#RUN mkdir cv-project &&\
#cd cv-project &&\
#git clone https://github.com/changh95/cpp-cv-project-template.git . &&\
#git checkout "develop" &&\
#pip3 install pyyaml &&\
#./setup.py
# 프로젝트에서 생성된 파일은 HOST에 MOUNT된 플더를 이용한다.
VOLUME /docker_share
RUN ln -s /docker_share $HOME

 

 

[ 출처 ]
https://www.cv-learn.com/20210808-docker-for-slam/ 

 

728x90

댓글