Dockerfile and package-json are in different folders

23 Views Asked by At

i am trying to build my react app, however, for the purpose of the project, the Dockerfile must be in the compose/cloud/ folder (it cannot be in the root), here is my folder structure

my-frontend-app/
│
├── compose/
│   └── cloud/
│       └── Dockerfile
│
├── src/
│   ├── components/
│   │   └── ...
│   ├── pages/
│   │   └── ...
│   ├── App.js
│   ├── index.js
│   └── ...
│
├── public/
│   ├── index.html
│   └── ...
│
├── package.json
├── package-lock.json

here is my dockerfile

FROM node:18-alpine as build-stage
WORKDIR /app

RUN cd . .
RUN cd . .
COPY . compose/cloud/
RUN npm install
RUN npm run build

FROM nginx:alpine
RUN rm -rf /usr/share/nginx/html/*
COPY --from=build-stage /app/build /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

whenever i try to build the image i keep getting this error (i run the command the build the image from inside cloud folder where Dockerfile is located)

#9 [build-stage 3/7] RUN cd . .
#9 DONE 0.3s

#10 [build-stage 4/7] RUN cd . .
#10 DONE 0.4s

#11 [build-stage 5/7] COPY . compose/cloud/
#11 DONE 0.0s

#12 [build-stage 6/7] RUN npm install
#12 1.414 npm ERR! code ENOENT
#12 1.414 npm ERR! syscall open
#12 1.415 npm ERR! path /app/package.json
#12 1.416 npm ERR! errno -2
#12 1.422 npm ERR! enoent Could not read package.json: Error: ENOENT: no such file or directory, open '/app/package.json'
#12 1.422 npm ERR! enoent This is related to npm not being able to find a file.

what should my dockerfile be? Thanks

1

There are 1 best solutions below

0
larsks On

A Dockerfile can only reference files relative to the build context. The build context is the directory specified as the final argument to docker build. Normally the Dockerfile is located at the top level of the build context, but you can use a Dockerfile located somewhere else with the -f option.

With your Dockerfile in compose/cloud/Dockerfile, you could run, from the top-level directory:

docker build -t my_image_tag -f compose/cloud/Dockerfile .

Because your build context is the top-level directory, you could do things like this:

COPY package.json /app/package.json

or:

COPY compose/cloud/ compose/cloud/

Etc.