我想在Docker容器中运行Rails应用程序并通过localhost:3000
从浏览器访问它,而在容器中运行的Rails应用程序侦听端口3001。
1)我创建一个docker compose文件并构建它。
FROM ruby:2.6.1-slim
LABEL maintainer = "Foo Bar [email protected]"
RUN apt-get update
RUN echo 'debconf debconf/frontend select Noninteractive' | debconf-set-selections
RUN apt-get install -y --no-install-recommends apt-utils
# Install necessary tools
RUN apt-get install -y vim && \
apt-get install -y git && \
apt-get install -y curl && \
apt-get install -y nodejs && \
apt-get install -y bash-completion && \
apt-get install -y build-essential patch ruby-dev zlib1g-dev liblzma-dev && \
apt-get install -y libsqlite3-dev
RUN gem install bundler
RUN gem install nokogiri
RUN gem install rails
RUN mkdir -p /projects
WORKDIR /projects
2)我通过运行docker run -it --rm -p 3000:3001 -v /path/to/my/projects:/projects rails /bin/bash
创建一个容器
docker ps
给出以下内容:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
2a8e30016a87 rails "/bin/bash" 4 minutes ago Up 4 minutes 0.0.0.0:3000->3001/tcp serene_turing
3)在我的Rails应用程序文件夹的容器中,我运行bundle && rails s -p 3001
并获取
=> Booting Puma
=> Rails 5.2.2.1 application starting in development
=> Run `rails server -h` for more startup options
Puma starting in single mode...
* Version 3.12.0 (ruby 2.6.1-p33), codename: Llamas in Pajamas
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://localhost:3001
Use Ctrl-C to stop
当我在浏览器中输入localhost:3000
时,我得到了
This site can’t be reached The connection was reset.
Try:
* Checking the connection
* Checking the proxy and the firewall
ERR_CONNECTION_RESET
知道什么是错的吗?
顺便说一句,用
docker run -it --rm -p 3000:3000 -v /path/to/my/projects:/projects rails /bin/bash
和
bundle && rails s
一切正常。
您正在从localhost:3000
重置连接,因为Puma服务器绑定到容器内部的127.0.0.1
,如日志所示:
* Environment: development
* Listening on tcp://localhost:3001
所以你需要从任何接口允许它允许它在0.0.0.0
上监听,这样你就可以从外部访问它。尝试将rails s
命令更改为以下内容:
rails s -b 0.0.0.0 -p 3001