Python – Docker jupyter notebook uses the container id as the ip, localhost

Docker jupyter notebook uses the container id as the ip, localhost… here is a solution to the problem.

Docker jupyter notebook uses the container id as the ip, localhost

I’m trying to run a jupyter notebook in python 3-based Docker. The notebook starts but shows the container ID as the IP. If I change it to “localhost:” in my browser after opening the link, it does work.

How do I get it to work and show localhost:in the url? /OS: Ubuntu 18.04/

Edit: I’ve tried jupyter/minimal-notebook which works, shows localhost, But it’s based on ubuntu 18.04, which isn’t compatible with some packages I want to use later in my notebook.

docker file:

FROM python:3
RUN apt-get -y update \
&& apt-get upgrade -y \
&& apt-get install -y \
    curl \
    vim \
    xterm
RUN pip install --upgrade pip
RUN pip install --no-cache-dir jupyter numpy matplotlib
# Add Tini. Tini operates as a process subreaper for jupyter. This prevents
# kernel crashes.
ENV TINI_VERSION v0.6.0
ADD https://github.com/krallin/tini/releases/download/${TINI_VERSION}/tini /usr/bin/tini
RUN chmod +x /usr/bin/tini
ENTRYPOINT ["/usr/bin/tini", "--"]

EXPOSE 8888
CMD ["jupyter", "notebook", "--port=8888", "--no-browser", "--ip=0.0.0.0", "--allow-root"]

Run after building

docker run --rm -it -p 8888:8888 -v "$PWD":/home/work e4b37115446d

Output:

[I 11:48:12.580 NotebookApp] Writing notebook server cookie secret to /root/.local/share/jupyter/runtime/notebook_cookie_secret
[I 11:48:12.826 NotebookApp] Serving notebooks from local directory: /
[I 11:48:12.826 NotebookApp] 0 active kernels
[I 11:48:12.826 NotebookApp] The Jupyter Notebook is running at:
[I 11:48:12.826 NotebookApp] http://3b906c2d97f3:8888/?token=06d43a78966a7b7e5fd04318183fa3e7af5bca7542477d31
[I 11:48:12.826 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
[C 11:48:12.827 NotebookApp] 

Copy/paste this URL into your browser when you connect for the first time, to login with a token:
        http://3b906c2d97f3:8888/?token=06d43a78966a7b7e5fd04318183fa3e7af5bca7542477d31&token=06d43a78966a7b7e5fd04318183fa3e7af5bca7542477d31

Solution

Use the --hostname flag when running the container. If left blank, it defaults to the container name.

docker run --rm  -it -p 8888:8888 --hostname localhost jup

Runtime:

[I 14:58:32.508 NotebookApp] The Jupyter Notebook is running at:
[I 14:58:32.508 NotebookApp] http://localhost:8888/?token=0e59cd9003b843f529b9bc6e7b39921001ddfdb253c029e9

Related Problems and Solutions