我有一个带有Rails API的服务的小项目:装有rails API的容器行为不如我所愿。
这是我的docker-compose.yml
:
version: '3'
services:
mynab_api:
image: 'myname/my_api:latest'
ports:
- '3001:3001'
这是服务的
Dockerfile
:FROM ruby:2.5.3-alpine3.8
# Minimal requirements to run a Rails app
RUN apk add --no-cache --update build-base \
linux-headers \
git \
sqlite-dev \
nodejs \
tzdata
ENV APP_PATH /usr/src/app
# Different layer for gems installation
WORKDIR $APP_PATH
ADD Gemfile $APP_PATH
ADD Gemfile.lock $APP_PATH
RUN bundle install
# Copy the application into the container
COPY . $APP_PATH
CMD ["bundle", "exec", "rails", "server", "-p", "3001"]
当我运行
$ docker-compose up
时,服务会启动,并且不会崩溃。如果运行$ docker-compose ps
,则服务已启动。问题是,如果我进入浏览器访问http://localhost:3001
,该服务似乎已关闭(尽管仍处于启动状态)。我发现的解决方法是,将
Dockerfile
(CMD [“bundle”,“exec”,“rails”,“server”,“-p”,“3001”])中的默认命令替换为CMD ["bundle", "exec", "rails", "server"]
默认情况下,该端口在端口3000上发出光。然后在
docker-compose.yml
中,将计算机上的端口3001映射到容器中的端口3000。version: '3'
services:
mynab_api:
image: 'myname/my_api:latest'
ports:
- '3001:3000'
这个工程找到。为什么第一个版本不起作用?
编辑:这是
telnet
给的-> % telnet localhost 3001
Trying ::1...
Connected to localhost.
Escape character is '^]'.
Connection closed by foreign host.
最佳答案
首先,您可以按如下所示修改docker-compose.yml
以在屏幕上查看服务器输出:
version: '3'
services:
mynab_api:
image: 'myname/my_api:latest'
ports:
- '3001:3001'
tty: true
您还应该尝试按以下方式修改
CMD
中的Dockerfile
:CMD ["bundle", "exec", "rails", "server", "-p", "3001", "-b", "0.0.0.0"]
如果运行
rails server --help
,您将看到--binding
标志的以下内容:Binds Rails to the specified IP - defaults to 'localhost' in development
and '0.0.0.0' in other environments'
您会发现在使用Docker容器(至少在开发中)或运行虚拟机(Virtualbox或其他)时需要指定此标志。
关于ruby-on-rails - docker未捕获`rails s -p`命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53934652/