How to install homebrew on Ubuntu inside Docker container

The new correct way is:

RUN apt-get update && \
    apt-get install -y -q --allow-unauthenticated \
    git \
    sudo
RUN useradd -m -s /bin/zsh linuxbrew && \
    usermod -aG sudo linuxbrew &&  \
    mkdir -p /home/linuxbrew/.linuxbrew && \
    chown -R linuxbrew: /home/linuxbrew/.linuxbrew
USER linuxbrew
RUN /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"

Gabriel's answer mostly worked for me, but was missing one step. I needed to chown the /home/linuxbrew/.linuxbrew folder to the user that would be running Homebrew:

USER root
RUN chown -R $CONTAINER_USER: /home/linuxbrew/.linuxbrew

Is there a reason you can't use the official image (docker pull linuxbrew/linuxbrew)? It is based on Ubuntu 16.04 / Xenial.

If you must use Bionic (18.04), the correct way to install homebrew will be to follow the steps in the official Dockerfile.

But to get your Dockerfile working, you need to install ruby, create a non-root user and execute the installation script as that user. Like so,

FROM ubuntu:18.04

RUN apt-get update && \
    apt-get install build-essential curl file git ruby-full locales --no-install-recommends -y && \
    rm -rf /var/lib/apt/lists/*

RUN localedef -i en_US -f UTF-8 en_US.UTF-8

RUN useradd -m -s /bin/bash linuxbrew && \
    echo 'linuxbrew ALL=(ALL) NOPASSWD:ALL' >>/etc/sudoers

USER linuxbrew
RUN sh -c "$(curl -fsSL https://raw.githubusercontent.com/Linuxbrew/install/master/install.sh)"

USER root
ENV PATH="/home/linuxbrew/.linuxbrew/bin:${PATH}"

PS: I have added --no-install-recommends to ignore optional dependencies and rm -rf /var/lib/apt/lists/* to remove apt-get leftovers thus reducing the image size. Also, locales is added to install UTF-8 or brew will throw a warning when you run the command.