Home > front end >  express is not loading static folder with docker
express is not loading static folder with docker

Time:01-18

I'm running webpack client side and express for server with docker the server will run fine but express won't load the static files

folder structure

client
 docker
  Dockerfile
 src
  css
  js
 public


server
 docker
  Dockerfile
 src
  views

client dockerfile

FROM node:19-bullseye

WORKDIR /usr/src/app

RUN curl -f https://get.pnpm.io/v6.16.js | node - add --global pnpm

COPY  package*.json ./

RUN pnpm install

COPY . .

EXPOSE 8080

CMD ["pnpm", "start"]

Server dockerfile

FROM node:19-bullseye

WORKDIR /usr/src/app

RUN curl -f https://get.pnpm.io/v6.16.js | node - add --global pnpm

COPY  package*.json ./

RUN pnpm install

COPY . .

EXPOSE 8081

CMD ["pnpm", "start"]

docker compose

version: '3.8'
services:
  api:
    image: server
    ports:
      - "8081:8081"
    volumes:
      - ./server/:/usr/src/app
      - /usr/src/app/node_modules

  client:
    image: client
    stdin_open: true
    ports:
      - "8080:8080"
    volumes:
      - ./client/:/usr/src/app
      - /usr/src/app/node_modules

express

import path from 'path'
import { fileURLToPath } from 'url'
import express from 'express'

const __dirname = path.dirname(fileURLToPath(import.meta.url))

const app = express()
const port = 8081

// view engine
app.set("views", path.join(__dirname, 'views'));
app.set("view engine", "pug");
app.locals.basedir = app.get('views')

// Middlewares
app.use(express.static(path.resolve(__dirname, '../../client/public/')))

app.get('/', (req, res) => {
  res.render('pages/home')
})

app.listen(port)

the closest thing that comes to my mind is that the public folder is not being copied by docker since this folder will be generated once i run the webpack server, or what might be causing this issue ?

CodePudding user response:

The issue is going to be that you are not adding the folder /client/public to the server docker container.

Because of your folder structure, you could add the following line to server/dockerfile

copy ../../client/public ./client/public

then you would need to update your path statement in express.js

let p = path.resolve(__dirname, '../../client/public/');
if(!fs.existsSync(p)){
  p = path.resolve(__dirname, './client/public/');
}

app.use(express.static(p))

The other option you have is to copy the whole project into both docker files and set the CWD, however, this method is not preferred. For example your server file would become

FROM node:19-bullseye

WORKDIR /usr/src/app

RUN curl -f https://get.pnpm.io/v6.16.js | node - add --global pnpm

COPY  package*.json ./

RUN pnpm install

COPY ../../ ./

WORKDIR /usr/src/app/server/src

EXPOSE 8081

CMD ["pnpm", "start"]

You can also inspect the file / folder structure by using docker exec

  • Related