Search code examples
dockerdocker-composeyarnpkg

Install and run yarn inside the docker container


I have docker build which works fine. But i want to install version specific yarn inside the container(it is the task) and run it after building, cause i dont want rebuild the container for install new dependecies. Current Dockerfile and docker-compose.yml

Dockerfile:

FROM node:16.17.0-alpine 

WORKDIR /front

COPY package.json .

RUN yarn install

COPY . .

CMD ["yarn", "start"]

ENV PORT 8000

EXPOSE $PORT

docker-compose.yml

version: "3.8"

services: 
  frontend: 
    build: 
      context: .
      dockerfile: Dockerfile
      args:
        NODE_MAJOR: '16.17.0'
        YARN_VERSION: '1.22.19'
    image: front-dev:1.0.0
    container_name: front-dev
    volumes:
      - .:/front:cached
      - ./node_modules:/front/node_modules
    stdin_open: true
    tty: true
    env_file:
      - .env
    ports:
      - "8000:8000"
    environment:
      - NODE_ENV=development
    cpu_shares: 512
volumes:
  node_modules:

Solution

  • Install yarn with apk(equivalent for apk in alpine). Move yarn commands from Dockerfile to docker-compose.yml(like below)

    Dockerfile:

    FROM node:16.17.0-alpine 
    
    WORKDIR /frontend
    
    COPY package.json yarn.lock ./
    
    RUN set -eux \
        & apk add \
            --no-cache \
            yarn
    
    ENV PORT 8000
    
    EXPOSE $PORT
    

    docker-compose.yml

    version: "3.8"
    
    services: 
      front: 
        build: 
          context: .
          dockerfile: Dockerfile
          args:
            NODE_MAJOR: '16.17.0'
            YARN_VERSION: '1.22.19'
        image: front-dev:1.0.0
        container_name: front-dev
        volumes:
          - .:/frontend
          - ./node_modules:/frontend/node_modules
        stdin_open: true
        tty: true
        env_file:
          - .env
        ports:
          - "8000:8000"
        environment:
          - NODE_ENV=development
        cpu_shares: 512
        command: 'yarn start'
    volumes:
      node_modules:
    

    P.S It is make building process much more faster.