skip to Main Content

I am trying to use a shared external volume (state) for four services composed by docker. However, I am noticing that my state is not being stored for some reason. Below is my docker-compose.yml file.

version: "3"

services:
  plus:
    build: ./addition
    image: plus_image
    volumes:
      - state:/state
  minus:
    build: ./subtraction
    image: minus_image
    volumes:
      - state:/state
  multiply:
    build: ./multiplication
    image: multiply_image
    volumes:
      - state:/state
  divide:
    build: ./division
    image: divide_image
    volumes:
      - state:/state

volumes:
  state:
    external: true

Below is the code for the addition application

import sys, os

STATE_DIR = './state'

def add(op1, op2):
    result = op1 + op2
    return result

def getOperand():
    value = 0
    if os.path.exists(STATE_DIR + '/value'):
        print('exits')
        with open(STATE_DIR + '/value', 'r') as f:
            if f.readable():
                value = int(f.read().strip())
    print(value)
    return value

def save(value):
    print('saivng')
    if(not os.path.exists(STATE_DIR)):
        os.makedirs(STATE_DIR)
    with open(STATE_DIR + '/value', 'w') as f:
        f.write(str(value))

if __name__ == '__main__':
    numArgs = len(sys.argv)
    if(numArgs == 2):
        try:
            op1 = getOperand()
            op2 = int(sys.argv[1])
        except:
            print('Invalid input!')
            exit(1)
    else:
        print('Usage: python3 <operation>.py op1')
        exit(1)
    result = add(op1,op2)
    save(result)
    print(result)

Running

docker run plus_image 10

should output 10 for the first run.

Running the same command again, it must print 20 (10 from input + 10 from the volume)

Directory structure for this project

.
 |-division
 | |-division.py
 | |-Dockerfile
 |-subtraction
 | |-Dockerfile
 | |-subtraction.py
 |-multiplication
 | |-Dockerfile
 | |-multiplication.py
 |-addition
 | |-Dockerfile
 | |-addition.py
 |-docker-compose.yml

If you have come across such an issue, kindly help. Thanks a lot!

2

Answers


  1. Use absolute path instead of relative path:

    STATE_DIR = '/state'
    

    Otherwise, if you want use relative path, verify the WORKDIR used in the Dockerfile, then mount the shared volume in the proper folder

    Login or Signup to reply.
  2. try

    docker-compose run plus 10
    

    by command

    docker run plus_image 10
    

    you run container from image plus_image and you don’t use compose file

    by

    docker-compose run plus
    

    you run service plus (witch use image plus_image) from your compose file

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search