alvarezsh
alvarezsh

Reputation: 503

How can I work with NodeJS and Docker Compose with volumes?

I'm trying to make it work nodejs with docker-compose and volumes, I want to edit my code, that's why I should use volumes.

when I do not put volumes in the docker-compose.yml file, it work!. But with volumes no work.

Any idea?

This is my docker-compose.yml:

version: "3.2"
services:
 node:
   container_name: node_app
     build:
      context: ./
      dockerfile: dockerfiles/Dockerfile
     user: "node"
     environment:
       - NODE_ENV=production
     volumes:
       - .:/home/app
     ports:
       - "3000:3000"

This is my Dockerfile:

FROM node:carbon-stretch
WORKDIR /home/app
COPY package*.json ./
RUN npm i express -S
COPY . .
EXPOSE 3000
CMD [ "npm", "start" ]

This is my package.json:

{
  "name": "docker_web_app",
  "version": "1.0.0",
  "description": "Node.js on Docker",
  "author": "First Last <test@gmail.com>",
  "main": "server.js",
  "scripts": {
     "start": "node server.js"
   }
 }

This is my server.js:

'use strict'
 const express = require('express')

 // Constants
 const PORT = 3000
 const HOST = '0.0.0.0'

 // App
 const app = express()
 app.get('/', (req, res) => {
   res.send('Hello world\n')
 });

 app.listen(PORT, HOST)
 console.log(`Running on http://${HOST}:${PORT}`)

Thanks!

Upvotes: 0

Views: 1006

Answers (2)

yamenk
yamenk

Reputation: 51906

The problem is that when you mount the folder . onto /home/app, all the content in /home/app gets overshadowed by the content of . on the host. This effectively removes the things introduced by RUN npm i express -S

To solve this you need to isolate the code that you want to edit into a separate folder (if that is already not the case)

volumes:
  - ./code:/home/app/code

Upvotes: 2

Muh faris
Muh faris

Reputation: 196

Try to parse your docker-compose file to the valid yaml format, you can try again:

version: "3.2"
services:
 node:
     container_name: node_app
     build:
      context: ./
      dockerfile: dockerfiles/Dockerfile
     user: "node"
     environment:
       - NODE_ENV=production
     volumes:
       - .:/home/app
     ports:
       - "3000:3000"

Upvotes: 0

Related Questions