Search code examples
dockerdocker-composecookiecutter-djangocaprover

Sharing a file between a persistent and a non persistent Docker Container


I'm using Caprover with Docker to run a Django project (Django-Cookiecutter) which is non persistent. I'm also running a persistent app on the same server which imports csv data. I need the two apps to basically share a file together. This is how i imagined it:

  1. The importer app imports csv data and stores it as a json file inside a specific folder.
  2. The Django app accesses the json file in that folder and uses a script i wrote to import the json into the database. I'm struggling to understand how i can access the folder inside my importer app containing the json file from my django app. Does anyone have an idea on how i can make this happen between those two docker containers?

Solution

  • You can share a directory or file between the two containers by mounting the same directory in both containers. Here's a simple docker-compose example where two containers mount the same directory. Then the first container writes to a file and the second container reads from it.

    Example

    version: '3'
    
    services:
      writer:
        image: alpine
        command:
          [
            "sh",
            "-c",
            "echo hello from writer >/shared-writer/hello.txt"
          ]
        volumes:
          - .:/shared-writer
      reader:
        image: alpine
        depends_on:
          - writer
        command: [ "cat", "/shared-reader/hello.txt" ]
        volumes:
          - .:/shared-reader
    

    Notice:

    • They both mount the current directory.
    • The first container writes to a file inside the mounted volume.
    • The second container reads from same file inside the mounted volume.
    • The containers use different mount points (/shared-writer and /shared-reader) to demonstrate that the same directory from your host can be mounted in different locations in the containers.

    Output

    $ docker-compose up
    Starting shared-mount-example_writer_1 ... done
    Starting shared-mount-example_reader_1 ... done
    Attaching to shared-mount-example_writer_1, shared-mount-example_reader_1
    reader_1  | hello from writer
    shared-mount-example_writer_1 exited with code 0
    shared-mount-example_reader_1 exited with code 0