Python – How to run a Python server on a Docker container

How to run a Python server on a Docker container… here is a solution to the problem.

How to run a Python server on a Docker container

I want to run a Python HTTP server on a docker container.

My DockerFile looks like this:

FROM continuumio/anaconda3:latest

RUN apt-get -y update
RUN apt-get -y install linux-headers-amd64 build-essential libc-dev gcc

RUN conda install --yes gcc
RUN conda install --yes numpy
RUN conda install --yes scipy
RUN conda install --yes gensim
RUN pip install annoy

RUN conda config --add channels conda-forge
RUN conda install --yes spacy

RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

ADD my-app.tar /usr/src/app

WORKDIR /usr/src/app/source

I build the image using:

docker build -t my-app-poc .

Start the container and enter the command:

docker run -i -t -p 9998:9998

In the bash of the Docker image, I run the script:

python Service.py

Which starts correctly:

Wed Apr  5 13:09:51 2017 Server Starts - :9998

But when I enter the address on the host:

http://localhost:9998

Nothing happens. I’ve also tried putting EXPOSE 9998 at the end of DockerFile but it didn’t help.

If I enter the docker-machine address on the host:

http://192.168.99.100:9989/

It works. But I want to run that image on a regular server, not on my local machine – so everything should be exposed to localhost.

I tried it on Windows 7.

Do you know how to run it?

I’m glad I could get your help!

Solution

This may or may not be relevant, but I can’t add a comment, so you’ll get a separate reply!

In a Docker container, you might have to bind your application (bind) to a 0.0.0.0 host. See this link.

It seems to me (although I’ll have to learn more about the app to be sure) that you’re looking for a connection on the loopback interface. This exposes the listener only to the local machine. In contrast, 0.0.0.0 is used to expose the listener to all network interfaces on the machine. Especially in this case, the docker network adapter. For a more detailed explanation, see this post.

Related Problems and Solutions