2016-10-14 28 views
1

我有一個定義Ruby on Rails堆棧的Dockerfile。當構建Dockerfile時linux source命令不工作

這裏是Dockerfile:

FROM ubuntu:14.04 
MAINTAINER example <[email protected]> 

# Update 
RUN apt-get update 

# Install Ruby and Rails dependencies 
RUN apt-get install -y \ 
ruby \ 
ruby-dev \ 
build-essential \ 
libxml2-dev \ 
libxslt1-dev \ 
zlib1g-dev \ 
libsqlite3-dev \ 
nodejs \ 
curl 

RUN gpg --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 

RUN curl -sSL https://get.rvm.io | bash -s stable --rails 

RUN /bin/bash -c "source /usr/local/rvm/scripts/rvm" 

# Install Rails 
RUN gem install rails 

# Create a new Rails app under /src/my-app 
RUN mkdir -p /src/new-app 

RUN rails new /src/new-app 

WORKDIR /src/my-app 

# Default command is to run a rails server on port 3000 
CMD ["rails", "server", "--binding", "0.0.0.0", "--port" ,"3000"] 

EXPOSE 3000 

當我執行命令docker build -t anotherapp/my-rails-app .我收到以下錯誤:

Removing intermediate container 3f8060cdc6f5
Step 8 : RUN gem install rails
---> Running in 8c1793414e63
ERROR: Error installing rails:
activesupport requires Ruby version >= 2.2.2.
The command '/bin/sh -c gem install rails' returned a non-zero code: 1

它看起來像命令source /usr/local/rvm/scripts/rvm在生成過程中不能正常工作。

我不確定這是爲什麼發生。

+2

該命令正​​在工作,但是當命令結束時,shell將退出並且所有內容都會再次消失。 – tkausl

+3

你可能不應該使用rvm來安裝rails,但是如果你想鏈接所有'RUN's,因爲它們每個都創建一個新圖層,並且可能不知道你的bash採購 – bjhaid

+0

你讀過這個答案了嗎?http: //stackoverflow.com/a/25685004/1981061? – Griffin

回答

6

docker builder reference開始,每個RUN命令都是獨立運行的。這樣做RUN source /usr/local/rvm/scripts/rvm對下一個RUN命令沒有任何影響。

嘗試改變需要給定的源文件如下

RUN /bin/bash -c "source /usr/local/rvm/scripts/rvm ; gem install rails" 
1

這並不直接回答你的問題的操作,但它的另一種方式來處理這個問題。

Docker提供了一個officialRuby image。這是快速入門教程使用的Docker Compose and Rails圖片。正如您可以從他們的示例(下面)中看到的那樣,您可以將Gemfile.lock複製到映像中,然後運行bundle install而不必擔心RVM。

FROM ruby:2.2.0 
RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs 
RUN mkdir /myapp 
WORKDIR /myapp 
ADD Gemfile /myapp/Gemfile 
ADD Gemfile.lock /myapp/Gemfile.lock 
RUN bundle install 
ADD . /myapp 

你通常只有一個軌道使用Ruby的特定版本,以便RVM的管理紅寶石的多個版本不會有幫助能力的容器中運行的應用程序。

如果你很好奇官方圖像是如何製作的,Dockerfile在Github上。


至於爲什麼會發生這種情況。正如其他人指出的那樣,source命令在當前shell中執行該文件。每個RUN指令

... will execute any commands in a new layer on top of the current image and commit the results. The resulting committed image will be used for the next step in the Dockerfile.

RUN每個,ADDCOPY指令基本上開始在一個新的容器的新殼和執行命令。

1 RUN /bin/bash -c "source /usr/local/rvm/scripts/rvm" 
2 RUN gem install rails 

可以理解爲

1 Start a brand new shell 
    Execute: source /usr/local/rvm/scripts/rvm 
    Save the state of the file system as an image 
    Exit shell 

2 Start a brand new shell 
    Execute: gem install rails 
    ... 

當第1步完成,外殼(和你的一切來源進去),消失。