Skip to content

Docker Setup

Using Environment Variables

Add environment variables into the docker compose file [samplePythonApp.yml].

The provided example compose file contains one environment variable already, LOG_LEVEL. If this environment variable is not present [config.py] will take the value log_level from [config.json] instead.

---
version: '3.7'

services:
  samplePythonApp:
    image: samplepythonapp:v1.0.0
    container_name: samplePythonApp
    restart: on-failure
    expose:
    - 14000-14100
    volumes:
    - samplePythonApp_vol:/app/data:rw
    networks:
    - edgenet
    environment:
      LOG_LEVEL: info
      SAMPLE_VAR_1: 600
      SAMPLE_VAR_2: 75.56
      SAMPLE_VAR_3: Sample String
    tmpfs:
    - /temp:uid=5678,gid=5678

networks:
  edgenet:
    name: edgenet

volumes:
  samplePythonApp_vol:
    name: samplePythonApp_vol

...

These environment variables are now accessible within the python application.

print( os.getenv('LOG_LEVEL') )
print( os.getenv('SAMPLE_VAR_1') )
print( os.getenv('SAMPLE_VAR_2') )
print( os.getenv('SAMPLE_VAR_3') )
>> info
>> 600
>> 75.55
>> Sample String

Using Docker Volumes

In the provided example docker compose file [samplePythonApp.yml], a single read/write volume is specified.

---
version: '3.7'

services:
  samplePythonApp:
    volumes:
    - samplePythonApp_vol:/app/data:rw

volumes:
  samplePythonApp_vol:
    name: samplePythonApp_vol

...

Read and write to this directory /app/data/ within the python application.

file_path = '/app/data/sample.txt'

# Write to the file
with open(file_path, 'w') as file:
    file.write('This is a sample text file.')

# Read from the file
with open(file_path, 'r') as file:
    content = file.read()

print('File content:', content)

Create subdirectories within /app/data within the python application.

import os
import csv

# Create subdirctories within /app/data/
text_sub_dir = '/app/data/text_files/'
csv_sub_dir = '/app/data/csv_files/'
os.makedirs(text_sub_dir, exist_ok=True)
os.makedirs(csv_sub_dir, exist_ok=True)

# File paths
text_file_path = os.path.join(text_sub_dir, 'sample.txt')
csv_file_path = os.path.join(csv_sub_dir, 'data.csv')

# Write to the text file
with open(text_file_path, 'w') as file:
    file.write('This is a sample text file in a subdirectory.')

# Read from the text file
with open(text_file_path, 'r') as file:
    content = file.read()

print('Text file content:', content)

# Sample CSV data
csv_data = [
    ['Name', 'Age', 'City'],
    ['Alice', 30, 'New York'],
    ['Bob', 25, 'Los Angeles'],
    ['Charlie', 35, 'Chicago']
]

# Write to the CSV file
with open(csv_file_path, 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerows(csv_data)

# Read from the CSV file
with open(csv_file_path, 'r') as file:
    reader = csv.reader(file)
    csv_content = list(reader)

print('CSV file content:')
for row in csv_content:
    print(row)