dockerlearner
dockerlearner

Reputation: 13

How to write a file to the host when using Docker?

Very new to Docker here.

I have the following very simple Dockerfile

FROM python
COPY . /app
WORKDIR /app
RUN pip install my_api.tar.gz
RUN pip install -r requirements.txt
CMD python ./main.py

And my main.py is just

import pandas as pd
import glob, os
import my_api

def main():
    isins_df = my_api.getInfo()
    isins_df.to_csv('data_from_docker.csv', index = False)
    print('\noutput df: \n{}'.format(isins_df))


if __name__ == "__main__":
    main()

The API comes back with the correct data. I am stuck when it comes to saving the result to the host. How can this be done?

Thanks

Upvotes: 1

Views: 538

Answers (1)

ruohola
ruohola

Reputation: 24038

You can add a VOLUME to your Dockerfile:

FROM python
COPY . /app
WORKDIR /app
VOLUME /app
RUN pip install my_api.tar.gz
RUN pip install -r requirements.txt
CMD python ./main.py

Then when running that image you need to pass the --volume flag to mount that volume to some path on the host machine:

docker build -t my_image .
docker run --volume=/path/on/host:/app my_image

If you wish to mount the volume to the directory where your building your Dockerfile, you can do it like this:

docker build -t my_image .
docker run --volume=$(pwd):/app my_image

Both of these will make it so that the contents of the container's /app directory and the specified directory on your host machine are "in sync", so the file your script creates in the container will appear on your host also.

Upvotes: 2

Related Questions