Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Question: How to set env for DockerImage or ServerContainer #670

@sasa-buklijas

Description

@sasa-buklijas

What are you trying to do?

I am trying to send some env to my FastAPI DockerImage or ServerContainer.

Where are you trying to do it?

This is code that I am using:

# Redis
redis = RedisContainer('redis:latest')
redis.start()
redis_container_host_ip = redis.get_container_host_ip()
os.environ['REDIS_HOST'] = redis_container_host_ip
redis_container_port = redis.get_exposed_port(redis.port)
os.environ['REDIS_PORT'] = redis_container_port
redis_stream = 'test_stream'
os.environ['REDIS_STREAM'] = redis_stream

# Postgres
postgres = PostgresContainer('postgres:16-alpine', driver=None, username='postgres', dbname='postgres', password='1234')
script = Path(__file__).parent / "dump-20240514.sql"
postgres.with_volume_mapping(host=str(script), container=f"/docker-entrypoint-initdb.d/{script.name}")
postgres.start()
os.environ['DATABASE_URL'] = postgres.get_connection_url()
  
# my FastAPI app
with DockerImage(path='./', dockerfile_path='Dockerfile.hr2ws', tag='test-srv:latest', clean_up=False) as image:
       with ServerContainer(port=8004, image=image) as fastapi_server:
            delay = wait_for_logs(fastapi_server, "Uvicorn running on http://0.0.0.0:8004", timeout=10.0)

Basically my app is using dotenv, to get env for redis and postgres.
Problem is I have not found way to send current os.environ to DockerImage.
I was thinking to hardcoded in additional Dockerfile.hr2ws.for_testcontiner file, but that will also not work because port is dynamically provided by testcontainer framework, also do not think that is correct way to do it.
I did look open PR an issues but was not able to find anything, only found similar for testcontainers-rs

Runtime environment

OSX 10.15.7
Python 3.12.2
testcontainers==4.7.2
Docker Desktop 4.15.0 (93002)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions