728x90

서론 : Docker, vite, npm에 대한 이해가 낮았어서 올바르게 빌드하기 보다는, container 내부에 접속해서 실행만 하는 과정입니다..  추후 좀 더 학습하게 되면 보완하겠습니다.  혹은 지적하실 부분 있다면 해주세요 
우선 제가 container 내부에서 run dev를 햇는지에 대한 과정정도로 이해해주시면 될 거 같습니다..

npx degit reduxjs/redux-templates/packages/vite-template-redux my-app

요즈음 자주 쓰는 vite를 통해서 app을 생성하겠습니다.
이후  해당 프로젝트 명으로 이동, 이후 설치 및 실행하면

cd  my-app
npm i
npm run dev

아래 사진과 같은 화면을 볼 수 있습니다.

cra에서와 마찬가지로 file생성 build  run 3가지 단계로 할려고 파일을 작성했는데 에러가 떴습니다..

FROM node:18-alpine

WORKDIR /app

COPY ["package.json", "package-lock.json*", "./"]

RUN npm install

COPY . .

EXPOSE 8080

CMD ["npm","run","dev"]

 

 

What's Next?
PS C:\ssgrepo\suhongFTpracticeRF\practice\my-app> docker run --publish 8000:8000 node-docker
node:internal/modules/cjs/loader:1080
  throw err;
  ^

Error: Cannot find module '/app/server.js'
    at Module._resolveFilename (node:internal/modules/cjs/loader:1077:15)
    at Module._load (node:internal/modules/cjs/loader:922:27)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:23:47 {
  code: 'MODULE_NOT_FOUND',
  requireStack: []
}

Node.js v18.17.1
PS C:\ssgrepo\suhongFTpracticeRF\practice\my-app> docker build --tag node-docker .
[+] Building 6.9s (10/10) FINISHED                                                                                                             docker:default
 => [internal] load .dockerignore                                                                                                                        0.0s
 => => transferring context: 2B                                                                                                                          0.0s 
 => [internal] load build definition from dockerfile                                                                                                     0.0s 
 => [internal] load metadata for docker.io/library/node:18-alpine                                                                                        0.8s 
 => [1/5] FROM docker.io/library/node:18-alpine@sha256:3482a20c97e401b56ac50ba8920cc7b5b2022bfc6aa7d4e4c231755770cf892f                                  0.0s 
 => [internal] load build context                                                                                                                        0.6s 
 => => transferring context: 1.31MB                                                                                                                      0.6s 
 => CACHED [2/5] WORKDIR /app                                                                                                                            0.0s 
 => CACHED [3/5] COPY [package.json, package-lock.json*, ./]                                                                                             0.0s 
 => CACHED [4/5] RUN npm install                                                                                                                         0.0s 
 => [5/5] COPY . .                                                                                                                                       4.1s 
 => exporting to image                                                                                                                                   1.3s 
 => => exporting layers                                                                                                                                  1.3s 
 => => writing image sha256:71266c50c7e333301fccb3a3138957b69f7e031c380d57056d1d72ce04880b87                                                             0.0s 
 => => naming to docker.io/library/node-docker                                                                                                           0.0s 

What's Next?
  View summary of image vulnerabilities and recommendations → docker scout quickview
PS C:\ssgrepo\suhongFTpracticeRF\practice\my-app> docker run --publish 8000:8000 node-docker
node:internal/modules/cjs/loader:1080
  throw err;
  ^

Error: Cannot find module '/app/server.js'
    at Module._resolveFilename (node:internal/modules/cjs/loader:1077:15)
    at Module._load (node:internal/modules/cjs/loader:922:27)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:23:47 {
  code: 'MODULE_NOT_FOUND',
  requireStack: []
}


이를 해결하기 위해서 구글링 해보다가 관련 게시글을 찾았습니다.
https://dev.to/ysmnikhil/how-to-build-with-react-or-vue-with-vite-and-docker-1a3l
관련 연습 코드 잇는 github 링크입니다. 

https://github.com/suhong99/container-practice 

 

GitHub - suhong99/container-practice

Contribute to suhong99/container-practice development by creating an account on GitHub.

github.com

 

How to use React or Vue with Vite and Docker

Introduction Hello fellow developers! With this guide, we will be creating a project that...

dev.to

우선 docker-compose.yml 파일을 루트에 생성합니다.

version: "3.4"
services:
  vite_docker:
    image: node:18-alpine
    container_name: vite_docker
    entrypoint: /bin/sh
    ports:
      - 8080:8080
    working_dir: /srv/app
    volumes:
      - type: bind
        source: ./
        target: /srv/app
    tty: true

관련 설명은  https://blockchainstudy.tistory.com/62에서한글로 번역되어 있습니다.

version : compose의 버전

services 안에 설명을 적습니다

컨테이너가 여러개 있을 수 있어서 우선

 vite_docker로 시작합니다. ( 이를 작성했기 때문에 container_name을 굳이 적지 않아도 됩니다)
  image : 어떤 이미지를 사용할 지 
 container_name : 이름 (위의 이름과 다를떄)
entrypoint  : 컨테이너 내에서 실행될 애플리케이션을 가리킵니다.  Alpine 이미지를 사용하고 있기 때문에  위에를 적어야한다 ( 틀렸을 수도 있습니다 ㅠ.)

ports : 연결할 포트 (Dockerfile과 동일한 기능) 추후 뒤에 부분은 vite.confing에 설정한 port와 같아야합니다.
working_dir : 작업할 디렉토리 . 컨테이너 접근시 해당위치로 갑지가

volumes :  해당 키워드로 호스트 파일을 사용할 수 있게 되고 빌드나 리스타트 해당 작업이 가능합니다.
이때 host 파일 업데이트를 bind 키워드를 통해 반영 가능합니다. 호스트 source를 target 위치로 옮길 수 있습니다 (제가 해석한 바에 의하면 ...)

tty는 컨테이너를 지속적으로 run하기 위해 사용합니다.





이후 vite.config.ts 에서 server 부분 코드를 추가해주셔야합니다.

export default defineConfig({
  plugins: [react()],
  server: {
    // open: true,
    host: true,
    port: 8080, // This is the port which we will use in docker
    watch: {
      usePolling: true,
    },
  },
  build: {
    outDir: "build",
    sourcemap: true,
  },
  test: {
    globals: true,
    environment: "jsdom",
    setupFiles: "src/setupTests",
    mockReset: true,
  },
})

server에서 host port watch 설정을 해야지만 윈도우 환경에서 docker가 가능하다고 합니다.

이후 도커 컴포즈 작업이  끝났으면 build하면 됩니다.

docker-compose up --build --no-recreate -d

처음 빌드할 떄는 위 키우워드를 사용해야 합니다. 이후에는

docker-compose up -d

 

compose의 경우 일반 dockerfile과 확인하는 명령어가 다르더군요.

docker-compose ps

를 통해 확인해야 합니다.

이후 해당 컨테이너로 이동후에 npm i 와 run dev를 하면  로컬환경에서 컨테이너를 확인할 수 있습니다.

docker exec -it vite_docker sh
npm i && npm run dev
 
 
docker 컨테이너 내부에서 나오려면 exit를 입력하면 됩니다.!




참고 링크

 

How to use React or Vue with Vite and Docker

Introduction Hello fellow developers! With this guide, we will be creating a project that...

dev.to

https://dev.to/ysmnikhil/how-to-build-with-react-or-vue-with-vite-and-docker-1a3l
https://blockchainstudy.tistory.com/62
https://www.youtube.com/watch?v=yIpDRI5cTdI

 

728x90

도커 데스크탑을 켜지않고 빌드하려하면 생기는 에러입니다. 
ERROR: error during connect: this error may indicate that the docker daemon is not running: Get "http://%2F%2F.%2Fpipe%2Fdocker_engine/_ping": open //./pipe/docker_engine: The system cannot find the file specified.










포트관련 게시글 링크

https://hbase.tistory.com/98

'DOCKER' 카테고리의 다른 글

docker vite typscript 이미지 생성하기  (0) 2023.09.09
도커와 redux-template를 통한 도커 실습  (0) 2023.09.07
728x90

서론 : CI, CD ,DOCKER등 막연하게 해야할 내용을 멘토님께 설명을 듣고, 좀 더 공부할 필요성을 느껴서 정리하게 되었습니다.

 


도커 사용 이유!

프로젝트를 진행할 때, 환경의 통일을 위해서 컨테이너를 이용해서 베포를 해야한다.  강의 내용을 듣거나, 블로그 내용을 따라하다 보면 종종 이 사람은 이렇게 했다는데 왜 나는 안되지 라는 의문이 생긴적이 많을 겁니다. 이는  운영체제, 노드 버전 등 개발 환경도 코드를 실행하는데 영향을 끼치기 때문입니다. 
이런 문제를 해결하기 위해서 컨테이너 개념이 생겼습니다.
특정한 가상환경에서 개발환경을 기록하고 실행을 한다면 모두가 똑같은 환경에서 작업을 할 수 있다!
이를 도커는  도커 파일을 통해 기록하고 해당 이미지를 생성해서 실행시키는 것으로 구현합니다.

가상 환경을 만드는 방법과 이를 보완해서 컨테이너를 생성하는 방법은 기존에도 있었지만, 도커가 인기있는 이유는 유저가 사용하기 쉽고 무료이기 때문입니다.

https://mysetting.io/slides/xxj85vnvey#/38

 

왕초보를 위한 도커 사용법

염근철님 슬라이드

mysetting.io

혹은 
https://docs.docker.com/get-started/

을 이용하시면 더 자세한 내용이 확인 가능합니다!

 

Overview of the get started guide

Get started with the Docker basics in this comprehensive overview, You'll learn about containers, images, and how to containerize your first application.

docs.docker.com




 

이제 저는 프론트엔드에 관심이 있는 개발자이기에 예시를 프론트 엔드와 관련지어서 설명하겠습니다.

예시로 사용할 프로젝트는  리덕스에서 기본으로 제공하는 프로젝트입니다.


https://github.com/reduxjs/redux-templates
                                              

 

GitHub - reduxjs/redux-templates: Official Redux templates for Vite, Create-React-App, and more

Official Redux templates for Vite, Create-React-App, and more - GitHub - reduxjs/redux-templates: Official Redux templates for Vite, Create-React-App, and more

github.com

 

일반 cra로 타입 redux 생성하기

npx create-react-app suhong --template redux-typescript

 

npm start하면 아래와 같은 화면이 보입니다. 이를 도커에서 실행해보겠습니다.

 

1.dockerfile 생성

 

dockerfile은 일종의 배치파일의 역할을 하는데, 이미지를 구성할 명령어를 저장해 놓은 파일입니다.

자체 DSL 언어로 이미지 생성 과정을 명시하는데, 각각의 명령어에 대한 자세한 설명은 아래 링크에서 확인할 수 있습니다. (좌측탭에 python java go 등등이 있네요)

https://docs.docker.com/language/nodejs/build-images/

 

Build your Node image

Learn how to build your first Docker image by writing a Dockerfile

docs.docker.com

FROM node:18-alpine
# ENV NODE_ENV=production

WORKDIR /app

COPY ["package.json", "package-lock.json*", "./"]

#RUN npm install --production
RUN npm install
COPY . .

CMD ["node", "server.js"]

예시에서는 node.js 서버까지 준비해서 실행하는 것이지만, 저는 간단하게 로컬에서 run만 확인하겠습니다.!
공식문서보고 차근차근 따라하셔도 좋을 것 같아요. .

하지만 그전에 공식문서에서 나온 코드를 하나하나 해석해볼게요.

공식 문서코드


첫 줄부터 이제 해석하면
FROMDocker images can be inherited from other images. Therefore, instead of creating our own base image, we’ll use the official Node.js image that already has all the tools and packages that we need to run a Node.js application.

 

FROM으로 사용할 이미지를 선택할 수 있습니다. 

그냥 저희만의 이미지 만들기보단 .node.js의 공식적인 이미지를 사용하면 쉽게 이미지 형성이 가능하다고 하네요.

 

NODE_ENV  : The NODE_ENV environment variable specifies the environment in which an application is running (usually, development or production).

 

개발환경인지 배포환경인지 결정하는 환경변수 값이라고 하네요

WORKDIR :. This instructs Docker to use this path as the default location for all subsequent commands. This way we do not have to type out full file paths but can use relative paths based on the working directory.

 

도커 파일을 실행할 경로를 선택하면, 이후에는 상대경로를 통해서 더 쉽게 경로 지정이 가능합니다. 이를 위해서 경로를 지정하는게 WORKDIR

 

COPY : Before we can run npm install, we need to get our package.json and package-lock.json files into our images. We use the COPY command to do this.

저희는 보통 깃을 이용해서 프로젝트를 클론 받을 때 npm i 를 통해서 노드 모듈들을 설치합니다.
도커에서도 프로젝트에 사용할 노드 모듈을 설치하기 위해서 package.json과 lock.json을 사용하는데 이를 copy키워드로 해당 파일을 옮겨줍니다.
이때 COPY의 매개변수로를 받을 파일들, 경로 가 있습니다.(마지막 매개변수가 경로)
위에서는 package.json과 lock.json을 ./ (app)에 복사해라는 것입니다.

RUN :  Once we have our files inside the image, we can use the RUN command to execute the command npm install.

런을 통해서 명령어를 실행할 수 있는데, package.json을 옮긴후 RUN을 통해서 모듈들을 가상환경에 설치

COPY : The next thing we need to do is to add our source code into the image. We’ll use the COPY command just like we did with our package.json files above.
이후 다른 소스코드들을 모두 옮겨줍니다.

 

CMDNow, all we have to do is to tell Docker what command we want to run when our image is run inside of a container.

 

이제 이미지 생성과 관련된 명령어를 입력이 끝났으니 어떤 명령어로 생성한 이미지를 실행할 지 결정해야 합니다. 이를 CMD를 통해서 합니다.

 

이를 바탕으로 내 dockerfile코드

 

FROM node:18-alpine

WORKDIR /app

COPY ["package.json", "package-lock.json*", "./"]

RUN npm install

COPY . .

CMD ["npm","run","start"]

 

2. 이미지 빌드

docker build --tag suhong .

전 프로젝트를 제 이름으로 생성하겠습니다 ( 예제에서는 node-docker) 였어요.

 

생성한 파일을 통해서 이미지를 빌드하는 키워드입니다. 이떄 --tag는 빌드할 이미지의 이름을 설정하는 건데, 
예제처럼 저도 node-docker라는 이름으로 이미지를 생성하겠습니다.
(이 과정에서 도커 데스크탑을 켰는지 먼저 확인해 주세요.

성공시

아래 명령어로 이미지가 생성됏는지 확인할 수 있습니다. 

docker images


3. 실행

이미지는 설정한 태그 이름 혹은 ID로 실행가능합니다.

docker run -p 3000:3000 suhong

포트맵핑을 하면 연결된 걸 볼 수 있습니다. 이떄  host :  container 의 포트입니다. ( 포트가 현재 3000으로 설정되어 있습니다..)

docker run -p 8080:3000 suhong

 

 

`

참고링크

 

 

 

 

 



https://stackoverflow.com/questions/40459280/docker-cannot-start-on-windows

 

Docker cannot start on Windows

Executing docker version command on Windows returns the following results: C:\Projects> docker version Client: Version: 1.13.0-dev API version: 1.25 Go version: go1.7.3 Git commit:

stackoverflow.com

https://tscofet.oopy.io/260778d6-d511-4b3a-9e6f-dfc2add821f6

 

[Devops Study] 05-2. 특화배포 - 개발서버 구축(Docker 파일구성)

참고

tscofet.oopy.io

https://dev.to/ysmnikhil/how-to-build-with-react-or-vue-with-vite-and-docker-1a3l

 

How to use React or Vue with Vite and Docker

Introduction Hello fellow developers! With this guide, we will be creating a project that...

dev.to

https://junhyunny.github.io/information/docker/docker-file-expose-instruction/

 

Dockerfile EXPOSE 명령어

<br /><br />

junhyunny.github.io

 

+ Recent posts