user13456401
user13456401

Reputation: 479

How to set dynamic values to Docker

I have this question, how can I dynamically change some values in docker once the image is built.

So basically I have this Dockerfile as below.

FROM python:3.7.7

WORKDIR /usr/src/app

COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt

COPY server.py /usr/src/app
COPY . /usr/src/app

EXPOSE 8083

# CMD ["python3", "-m",  "http.server", "8080"]
CMD ["python3", "./server.py"]

So currently the server is working as expected. But there is a variable in server.py that changing dynamically. Once the image is built, I can't change that variable as now the image is already built and that variable is always referring to the same value.

See server.py below:

from flask import Flask
app = Flask(__name__)
import linearregression

PORT = 8083

file_path = "./prices.csv" # variable I need to change


predicted_values = linearregression.runModel(file_path)

@app.route('/')
def hello_world():

    return "Predicted Values - " + str(predicted_values)

@app.route('/banuka')
def hi():
    return "Hi Jananath"

if __name__ == '__main__':
   app.run(host='0.0.0.0', port=PORT)

As above, I have another python file called linearregression.py which has a method runModel(file_path) which accepts a parameter in a String format and returns some values.

This path has to be changed every time I upload a different file or change the content in the same file. But I can't do this since the image is already built. How can I do this?

Upvotes: 1

Views: 801

Answers (1)

kofemann
kofemann

Reputation: 4423

You should try to define a variable with ENV in Dockerfile and start the container with '-e' option :

FROM python:3.7.7
...
ENV FILE_PATH=prices.csv
...
CMD ["python3", "./server.py"]

And in python code:

import os
from flask import Flask
app = Flask(__name__)
import linearregression

PORT = 8083

file_path = os.environ['FILE_PATH'])
....

and run it as:

docker run -e FILE_PATH=/path/to/prices.csv ...

Upvotes: 1

Related Questions