Search code examples
pythondockerflaskcondaminiconda

Docker image conda environment and flask


I would like to make a Flask API running into docker with a conda environment.

It seems that I can install the conda environment from the .yml file.

But I can't run the app when I do docker run.

I just have errors about files that do not exist

exec source activate flask_env && python app.py failed: No such file or directory

The flask API is based on a simple example:

from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/', methods=['GET'])
def hello_world():
    return jsonify({'message': 'Hello World'})

@app.route('/test', methods=['GET'])
def test():
    return jsonify({'test': 'test'})

if __name__ == "__main__":
    app.run(debug=True) # remember to set debug to False

The Dockerfile is:

FROM continuumio/miniconda3:latest

WORKDIR /app

# Install myapp requirements
COPY environment.yml /app/environment.yml
RUN conda config --add channels conda-forge \
    && conda env create -n myapp -f environment.yml \
    && rm -rf /opt/conda/pkgs/*

# Copy all files after to avoid rebuild the conda env each time
COPY . /app/

# activate the myapp environment
ENV PATH /opt/conda/envs/myapp/bin:$PATH

# Launch the API
CMD [ "source activate flask_env && python app.py" ]

And the environment file is:

name: myapp
channels:
  - conda-forge
  - defaults
dependencies:
  - flask=1.0.2
  - python=3.7.3

I tried a lot of thing but I can't make it works. Did I miss something ?

Thank you


Solution

  • See this:

    The CMD instruction has three forms:

    CMD ["executable","param1","param2"] (exec form, this is the preferred form)
    CMD ["param1","param2"] (as default parameters to ENTRYPOINT)
    CMD command param1 param2 (shell form)

    Here, you CMD is used as parameters of ENTRYPOINT(see this), so you have to use next format:

    CMD ["param1","param2"] (as default parameters to ENTRYPOINT)
    

    But, your command have && in it, so you have to enable shell in json format. So for your case, this could be next, FYI:

    CMD ["bash", "-c", "source activate flask_env && python app.py"]