我正在为一个简单的 rails/postgres 应用程序构建 docker 容器。 rails 应用程序已启动并正在监听端口 3000。我已为 rails 容器公开了端口 3000。但是, http://localhost:3000 正在响应 ERR_EMPTY_RESPONSE 。我认为 rails 容器应该可以在端口 3000 上访问。还有什么我需要做的吗?

greg@MemeMachine ~ $ docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED              STATUS              PORTS                    NAMES
eed45208bbda        realestate_web      "entrypoint.sh bash …"   About a minute ago   Up About a minute   0.0.0.0:3000->3000/tcp   realestate_web_1
a9cb8cae310e        postgres            "docker-entrypoint.s…"   About a minute ago   Up About a minute   5432/tcp                 realestate_db_1
greg@MemeMachine ~ $ docker logs realestate_web_1
=> Booting Puma
=> Rails 6.0.2.2 application starting in development
=> Run `rails server --help` for more startup options
Puma starting in single mode...
* Version 3.12.4 (ruby 2.6.3-p62), codename: Llamas in Pajamas
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://localhost:3000
Use Ctrl-C to stop
greg@MemeMachine ~ $ curl http://localhost:3000
curl: (52) Empty reply from server

Dockerfile
FROM ruby:2.6.3

RUN apt-get update -qq && apt-get install -y nodejs postgresql-client
RUN mkdir /myapp
WORKDIR /myapp
COPY Gemfile /myapp/Gemfile
COPY Gemfile.lock /myapp/Gemfile.lock
RUN gem install bundler -v 2.0.2
RUN bundle install
COPY . /myapp

# Add a script to be executed every time the container starts.
COPY entrypoint.sh /usr/bin/
RUN chmod +x /usr/bin/entrypoint.sh
ENTRYPOINT ["entrypoint.sh"]
EXPOSE 3000

# Start the main process.
CMD ["rails", "server", "-b", "0.0.0.0"]

docker-compose.yml
version: '3'
services:
  db:
    image: postgres
    volumes:
      - ./tmp/db:/var/lib/postgresql/data
    env_file:
      - '.env'
  web:
    build: .
    command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'"
    volumes:
      - .:/myapp
    ports:
      - "3000:3000"
    depends_on:
      - db
    env_file:
      - '.env'

入口点.sh
#!/bin/bash

# Compile the assets
bundle exec rake assets:precompile

# Start the server
bundle exec rails server

最佳答案

当您同时提供 ENTRYPOINTCMD 时, Docker combines them together into a single command 。如果您只是在构建图像时对其进行 docker run,入口点脚本将作为命令行参数传递命令部分 rails server -b 0.0.0.0;但它忽略了这一点,只启动 Rails 服务器本身(在这种情况下,没有 import -b 0.0.0.0 选项)。

通常的答案是不要尝试直接在入口点运行主进程,而是使用 exec "$@" 结束脚本以从附加参数运行命令。

在这种情况下,有两个附加位。 command: 文件中的 docker-compose.yml 表示需要在入口点中完成一些额外的设置(您不需要覆盖图像的命令来运行相同的服务器)。您还需要 bundle exec 提供的额外环境设置。将这一切移到入口点脚本中,您会得到

#!/bin/sh
# ^^^ this script only uses POSIX shell features

# Compile the assets
bundle exec rake assets:precompile

# Clean a stale pid file
rm -f tmp/pids/server.pid

# Run the main container process, inside the Bundler context
exec bundle exec "$@"

你的 Dockerfile 可以保持原样;您可以从 command: 文件中删除重复的 docker-compose.yml

关于ruby-on-rails - 无法在端口 3000 上访问 docker-compose rails 应用程序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61164093/

10-12 17:17
查看更多