Search code examples
linuxbashdocker

When installing Rust toolchain in Docker, Bash `source` command doesn't work


I am trying to create a docker image that will setup a Linux environment for building Rust projects. Here is my Dockerfile so far:

FROM ubuntu:16.04

# Update default packages
RUN apt-get update

# Get Ubuntu packages
RUN apt-get install -y \
    build-essential \
    curl

# Update new packages
RUN apt-get update

# Get Rust
RUN curl https://sh.rustup.rs -sSf | bash -s -- -y

The last thing I need to do is configure Rust, so that I can use cargo. The documentation says to use

source $HOME/.cargo/env

but when I try that in a RUN command in a Dockerfile, it says source is not recognized. Another option I found was to use

RUN /bin/bash -c "source ~/.cargo/env"

This does not error, but when I run my container, cargo is not a recognized command.

Either approach works from Bash when I have the container open, but I would like this to be automated as part of the image.

How can I integrate this into my Dockerfile?


Solution

  • You have to add the sourcing inside the .bashrc.

    This works:

    FROM ubuntu:16.04
    
    # Update default packages
    RUN apt-get update
    
    # Get Ubuntu packages
    RUN apt-get install -y \
        build-essential \
        curl
    
    # Update new packages
    RUN apt-get update
    
    # Get Rust
    RUN curl https://sh.rustup.rs -sSf | bash -s -- -y
    
    RUN echo 'source $HOME/.cargo/env' >> $HOME/.bashrc
    

    EDIT

    Instead of

    RUN echo 'source $HOME/.cargo/env' >> $HOME/.bashrc

    you can use

    ENV PATH="/root/.cargo/bin:${PATH}"

    which is a less bash-only solution