그럼 이제 구체적으로 실제 Docker를 사용하는 방법에 대해 정리해보도록 하자.
Docker를 사용하기 위해서는 먼저 사용하고자 하는 Docker Image를 만들어야 한다. Docker Image는 개발환경을 만들어주는 역할을 한다. 이 Docker Image를 통해 실질적으로 프로그램을 실행할 수 있는 환경을 만들어 주는 것이 Container이다.
- Images: A docker image contains everything you need to run your application. It is a template that holds a set of instructions needed to create a working container.
- Container: This is a running process/instance of an image. A docker container ‘contains’ everything your application needs to run and can run your application in any environment — as discussed above.
- Dockerfile: A dockerfile is a blueprint/set of instructions that defines how your image is built. It is a series of steps that you have defined, and that must happen before your image is successfully built.
- Docker hub: Think of Github. Docker hub is a registry that allows you to host your images and gives you access to a wide number of other docker images that you can pull and work with.
- Dockerignore: The .dockerignore file acts like the .gitignore file. It contains any file in your local application that you do not want in your docker image.
Docker를 활용해서 개발환경을 구축하기 위해서는 먼저 Docker Image를 만들어야 한다. Docker Image는 Dockerfile
을 이용해서 만들 수 있다.
Docker Image 만들기
작업할 폴더에서 Ubuntu18.04 버전으로 Dockerfile을 만들었다.
FROM ubuntu:18.04
RUN apt-get update
RUN apt-get -y install nodejs
RUN apt-get -y install npm
RUN npm install -g yarn
위 도커 파일을 실행하면 ubuntu 18.04 위에서 nodejs, npm, yarn을 순차적으로 설치하게 된다. docker image를 만들기 위한 명령어는 다음과 같다.
docker build --no-cache -t [imagename]:latest .
커맨드를 실행하고 나서 Docker Image파일을 검색해본다.
react-builder 라는 이름으로 이미지가 만들어졌다.
Docker Image 다운받기
Docker는 Docker Hub라는 사이트를 통해 도커 이미지를 공유할 수 있다. 터미널에서 docker search node
명령어를 사용하면 node 관련 도커 이미지를 인기 순으로 확인할 수도 있다.
예를 들어 node 16버전을 다운받고 싶다면 아래와 같이 명령어를 입력한다.
docker pull node:16
Docker compose
위와 같이 직접 생성하거나 다운받은 이미지를 이용해서 docker container를 생성하면 로컬에 설치하지 않고 다양한 개발환경을 구축할 수 있게 된다. docker-compose.yml
을 이용해서 간단하게 개발환경을 구축해보았다.
docker-compose.yml
version: '3.8'
services:
node:
image: 'node:16'
user: 'node'
working_dir: /home/node/app
environment:
- NODE_ENV=production
volumes:
- ./:/home/node/app
tty: true
ports:
- 3001:3000
- version : compose파일에서는 먼저 스키마 버전을 정의한다. 대부분의 경우 지원되는 가장 최신 버전을 사용하는 것이 좋다.
- services : 실행하려는 서비스, 또는 컨테이너 목록을 정의한다.
- image : 다운받아 활용할 컨테이너 이미지를 정의한다.
- command : 일반적으로
image
정의 가까운 곳에 실행할 명령을 표시한다.
vscode에서 remote-container extension을 설치하면 docker-compose 파일 설정대로 간단하게 컨테이너를 실행할 수 있다. 개발에 필요한 언어나 패키지 파일들은 컨테이너에 설치해서 사용하고 실행 파일들은 로컬 저장소에 저장하는 방식이다.
Reference
Get started with development Containers in Visual Studio Code
Getting Started With Docker in Your React.Js Application - The Basics