Docker-Compose - unable to change working_directory

Viewed 2481

In my Dockerfile I'm setting the working directory using: WORKDIR /usr/src/app and then later in the file I need to update it WORKDIR /usr/src/app/src/front to run some further build commands.

Now in my docker-compose when I want to run a specific npm run api, it has to be done from /usr/src/app. As I updated the WORKDIR in the Dockerfile itself, I've been trying to update the working directory using the following in my docker-compose however it doesn't seem to move into that specific directory - I see an error stating it can't find npm run start and on looking at its in the directory /usr/src/app instead of /usr/src/app/src/front as I've specified with working_dir

version: '3.4'

services:
  front:
    image: myimage
    working_dir: /usr/src/app/src/front
    ports:
      - 3000:3000
    command: ["npm", "run", "start"]

Is it even possible to update the working_dir like I'm trying to?

My Dockerfile looks like:

FROM node:12.18-alpine

ENV NODE_ENV=production

WORKDIR /usr/src/app

COPY package*.json ./

RUN npm install

COPY . .

RUN npm run build

# Build the frontend
RUN cd /usr/src/app/src/front \
    && npm install \
    && npm run build

COPY . .

Thanks.

1 Answers

Yes, it is possible to override WORKDIR as well as some other Dockerfile directives (ENTRYPOINT, CMD) at launch with docker run or in docker-compose.yml. You've done the overwriting right in the example, so the problem is somewhere else.

Also note that you can just cd to temporary change working directory in Dockerfile. For example:

RUN cd /usr/src/app \
    && npm run build \
    && cd src/front \
    && npm run build
    # and so on

When you use WORKDIR you set the default working directory. It is good to point to where your app's root is but it is quite unusual to use it to build an image.

Related