Docker: bind mounts not working as I expected

Most of the times I use Docker with volumes. But Now I am trying bind mounts for the first time and they are not working as I expected. I'm probably missing something or maybe not understanding completely they way they work.

Let's take this example. I have a React app created with create-react-app and it will run with a Rails backend based on a MySQL database.

My directory structure is:

App
├── docker
│   ├── api
│   │   └── Dockerfile
│   └── fe
│       ├── Dockerfile
│       ├── package.json
│       ├── package-lock.json
│       ├── public
│       ├── README.md
│       └── src
├── docker-compose.yml

I started by creating the docker-compose.yml file like this:

version: "3.7"

services:

  web:
    build: ./docker/fe/.
    ports: ["80:3000"]
    volumes:
      - type: bind
        source: "./docker/fe"
        target: "/app"

As you may see, I am mapping the directory ./docker/fe, where the React frontend is, to /app.

Inside ./docker/fe is the Dockerfile:

FROM node:8

WORKDIR /app

RUN npm install

CMD ["npm","start"]

I was expecting this to work, because my app files are all inside /app, mapped to ./docker/fe. At least I thought they would be! But when I run the docker-compose up --build command at the command line I get a build error, because it says there is no package.json file inside the /app directory.

On the other hand, when I use this other version of Dockerfile

FROM node:8

WORKDIR /app

ADD package.json .

ADD package-lock.json .

RUN npm install

ADD . .

CMD ["npm","start"]

this problem won't happen. It will find the package.json file and build the app correctly. But it won't run!

The fact is, it will say it can't find the React scripts. And it is no surprise, since when it is finished there is no node_modules directory inside ./docker/fe as it would be expected after running npm install.

I am confused.

Upvotes: 0

Views: 2740

Answers (1)

DevOps Dan
DevOps Dan

Reputation: 1853

Docker volumes are only mounted when image is run, not during build phase.

Add these back in to your Dockerfile:

ADD package.json .

ADD package-lock.json .

And/or:

ADD . .

Upvotes: 3

Related Questions