Docker Express use static directory

  docker, docker-compose, express, node.js

I am working off a tutorial to get MEAN stack application.
Without docker I start it with npm start server.js. This works fine, when i go to localhost:8888 I get index.html fine.
server.js redirects /app , which is app.controller.js.
Inside app.controller there is router.use('/'), express.static('app'); Which gives the path where index.html is. So it works fine.

With docker path doesnt work, so I get ‘cannot get /app/’

My Dockerfile

FROM node:14-alpine3.12

WORKDIR /app

RUN npm install 
&& npm install --save express 
&& npm install --save nodemon 
&& npm link [email protected] 
&& npm install --save rootpath
COPY package.json /app/package.json

CMD ["./tool_start.sh"]

tool_start just executes npm run start, which in package json starts ‘nodemon server.js’
My docker-compose, ignore mongo, I plan to use it in future only.

version: "2"
services:
  nodejs:
    build: .
    ports:
      - "8888:8888"
    volumes:
      - ./:/app
      - node_modules:/app/node_modules
  mongodb:
    image: mongo:4.0.14
    ports:
      - '27018:27017'
    volumes:
      - mongo_data:/data/db
volumes:
  node_modules:
  mongo_data:

server.js

require('rootpath')();
var express = require('express');
var app = express();

app.use('/app', require('./controllers/app.controller'));;

// make '/app' default route
app.get('/', function (req, res) {
    console.log('redirect')
    return res.redirect('/app');
});

// start server
var server = app.listen(8888, function () {
    console.log('Server listening at http://' + server.address().address + ':' + server.address().port);
});

app.controller.js

var express = require('express');
var router = express.Router();

router.use('/', function (req, res, next) {
    next();
});

// serve angular app files from the '/app' route
console.log(__dirname)
router.use('/', express.static('app'));

module.exports = router;

My html is just <label>hello</label> it is in app folder.

Ive tried in Dockerfile to COPY . /app. Then give give absolute path. Ive tried to use ‘path’ library so instead of router.use('/', express.static('app')); I had app.use('/', express.static(path.resolve('.'))); with . then ./ and /app/ etc. Nothing seems to work, its like it doest set that static path at all. The files are in the container, Ive checked with docker exec -it containerid sh.
I hope someone has any idea what is going on. Thank you!

Source: Docker Questions

LEAVE A COMMENT