简体   繁体   中英

Can't access docker containers from host

I have a simple image for a Rails service with the following Dockerfile:

FROM ruby:2.4.4
MAINTAINER sadzid.suljic@gmail.com

RUN apt-get update && apt-get install -y \
    build-essential \
    nodejs

RUN mkdir /app
WORKDIR /app

COPY Gemfile Gemfile.lock ./
RUN gem install bundler && bundle install

COPY . ./

EXPOSE 3000

CMD ["rails", "s", "-p", "3000"]

I built the image and ran the container with these commands:

docker build -t chat/users .
docker run -P --name users_service chat/users

I have this output on the host:

 $ docker ps
 CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                     NAMES
 23716591e656        chat/users          "rails s -p 3000"   6 minutes ago       Up 5 minutes        0.0.0.0:32774->3000/tcp   users_service

$ lsof -n -i :32774 | grep LISTEN
com.docke 32891 ssuljic   18u  IPv4 0x41c034d5d4627f5f      0t0  TCP *:filenet-re (LISTEN)
com.docke 32891 ssuljic   19u  IPv6 0x41c034d5d3beb9b7      0t0  TCP [::1]:filenet-re (LISTEN)

$ curl localhost:32774
curl: (52) Empty reply from server

When I run curl localhost:3000 inside the container I get the proper response from my API.

Does anyone know why I can't access the container from my host?

I'm using Docker for Mac with this version:

$ docker -v
Docker version 18.03.1-ce, build 9ee9f40

Some versions of Rails bind to localhost by default, which explains why you can access from within the container but not from the host (it's viewed as a different host).

Adding -b 0.0.0.0 to the CMD instruction should solve the problem.

Try:

docker run -p 3000:3000 --name users_service chat/users

This will map 3000 to 3000

http://localhost:3000

Looking into this more I think this was either and chrome issue or network issue as I was having the same issue:

Here is how I resolved it:

  1. Make sure your /etc/hosts file has 127.0.0.1 localhost (more than likely it's already there)

  2. Cleared Cookies and Cached files

  3. Cleared host cache

    Go to: chrome://net-internals/#dns click Clear Host Cache

  4. Restarted chrome

  5. Reset Network Adapter Note: This was unintentional so not sure if it was part of the fix or not, but wanted to include it in case.

Unfortunately I'm not sure which step fixed the problem

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