简体   繁体   中英

Unable to connect to express server hosted in Docker container from host machine

I'm trying to set up a dev environment inside a Docker container, using the container to compile and run my code, while the code itself resides on the host computer (ie my local machine). I've got the image built and running, but I can't connect to it.

My dockerfile:

# Dockerfile (tag: v3)
FROM node:latest

WORKDIR /tmp
COPY package.json /tmp/
RUN npm config set registry http://registry.npmjs.org/ && npm i

WORKDIR /usr/src/app
COPY . /usr/src/app/
RUN cp -a /tmp/node_modules /usr/src/app/ && npm run dll

ENV NODE_ENV=production
ENV PORT=4000
EXPOSE 4000

And then my docker-compose file:

# docker-compose.yml (tag: v4)
web:
  build: .
  ports:
  - "4000:4000"
  volumes:
  - .:/usr/src/app/:rw
  environment:
  - NODE_ENV=development
  command: >
    sh -c '
    if test -d node_modules;
    then
      echo node_modules_exists ;
    else
      cp -a /tmp/node_modules /usr/src/app/website;
    fi && 
    npm i && 
    npm start
    '

With this setup, I'd expect to be able to connect to localhost:4000 . The console output from the container that my express app is now listening on port 4000. I've also tried with 172.17.0.2:4000 , which is the IP address of the container when checking with docker inspect .

What other steps do I need to take to connect? I'm running Windows 10 and Docker 17.09.0-ce-win33 (13620), using Linux containers.

just remove these lines from the docker file and try to build and run.

ENV NODE_ENV=production
ENV PORT=4000

If this enabled you to hit localhost:4000, then the reason is that when you first build the image the production environment is exposing to port 4000. and when you run the docker-compose file ,you again specified the env as development. so both are trying to expose to port 4000. so it fails.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM