Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
feat: add DOCKER_NETWORK env var for RDS, EKS, ElastiCache container networking (#453)
Stephan Mielke82025ed83afe
diff --git a/README.md b/README.mdindex d9ebfa60..7876bf73 100644--- a/README.md+++ b/README.md@@ -635,12 +635,13 @@ ecs.stop_task(cluster="dev", task=task_arn)| `RDS_BASE_PORT` | `15432` | Starting host port for RDS containers || `RDS_TMPFS_SIZE` | `256m` | Tmpfs size for RDS database containers (when `RDS_PERSIST=0`). Set to `2g` or higher for large databases || `RDS_PERSIST` | `0` | Set `1` to use Docker named volumes for RDS containers instead of tmpfs. Storage grows dynamically with no fixed cap |+| `DOCKER_NETWORK` | _(unset)_ | Docker network for all container-backed services (RDS, EKS, ElastiCache, Lambda). Set to your Docker Compose network name so containers can reach each other. Replaces `LAMBDA_DOCKER_NETWORK` || `ELASTICACHE_BASE_PORT` | `16379` | Starting host port for ElastiCache containers || `PERSIST_STATE` | `0` | Set `1` to persist service state across restarts || `STATE_DIR` | `/tmp/ministack-state` | Directory for persisted state files || `LAMBDA_EXECUTOR` | `local` | Lambda execution mode: `local` (subprocess) or `docker` (container). `provided` runtimes and `PackageType: Image` always use Docker || `LAMBDA_STRICT` | `0` | Set `1` for AWS-fidelity mode: every Lambda invocation runs in a Docker container via the AWS RIE image; in-process fallbacks are disabled. Missing Docker surfaces as `Runtime.DockerUnavailable` instead of degrading to a subprocess. Opt-in because the default install doesn't require Docker |-| `LAMBDA_DOCKER_NETWORK` | _(unset)_ | Docker network for Lambda containers. Set to your Docker Compose network name so Lambda can reach MiniStack |+| `LAMBDA_DOCKER_NETWORK` | _(unset)_ | Legacy alias for `DOCKER_NETWORK` (Lambda only). Prefer `DOCKER_NETWORK` which covers all services || `LAMBDA_WARM_TTL_SECONDS` | `300` | How long an idle warm Lambda container stays in the pool before the reaper evicts it || `LAMBDA_ACCOUNT_CONCURRENCY` | `0` | Account-level concurrent-invocation cap (0 = unbounded). Match real AWS by setting to `1000`. Used to simulate `ConcurrentInvocationLimitExceeded` throttles || `SFN_MOCK_CONFIG` | _(unset)_ | Path to JSON file for Step Functions mock testing; compatible with AWS SFN Local format. Also accepts `LOCALSTACK_SFN_MOCK_CONFIG` |@@ -740,8 +741,9 @@ created for lambdas need to be killed manually.Additionally a volume is needed to mount the code (and extra layers). This must be set withthe LAMBDA_REMOTE_DOCKER_VOLUME_MOUNT environment variable. This must be a named volume (managed by docker).-If a ministack is not running on the default network, LAMBDA_DOCKER_NETWORK needs to be set, which will attach-the lambda to this network, making it posssible to access ministack (AWS) resources from the lambda.+If a ministack is not running on the default network, DOCKER_NETWORK needs to be set, which will attach+all container-backed services (Lambda, RDS, EKS, ElastiCache) to this network, making it possible to access+ministack (AWS) resources from the lambda. The legacy `LAMBDA_DOCKER_NETWORK` is still accepted as a fallback.Example docker compose file:```@@ -763,7 +765,7 @@ services:environment:DOCKER_SOCK: ${DOCKER_SOCK:-/var/run/docker.sock}LAMBDA_EXECUTOR: docker- LAMBDA_DOCKER_NETWORK: ${COMPOSE_PROJECT_NAME}_infra-network+ DOCKER_NETWORK: ${COMPOSE_PROJECT_NAME}_infra-networkLAMBDA_REMOTE_DOCKER_VOLUME_MOUNT: "{COMPOSE_PROJECT_NAME}_lambda-docker-volume"AWS_DEFAULT_REGION: ${AWS_REGION:-eu-central-1}AWS_SECRET_ACCESS_KEY: ${AWS_SECRET_ACCESS_KEY:-my_secret}diff --git a/docker-compose.yml b/docker-compose.ymlindex 056e5018..1221d19e 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -12,6 +12,7 @@ services:- REDIS_HOST=redis- REDIS_PORT=6379- RDS_BASE_PORT=15432+ # - DOCKER_NETWORK=ministack_default # Docker network for RDS/EKS/ElastiCache/Lambda containers- ELASTICACHE_BASE_PORT=16379volumes:- ./data/s3:/tmp/ministack-data/s3diff --git a/ministack/services/eks.py b/ministack/services/eks.pyindex a3779438..03a44606 100644--- a/ministack/services/eks.py+++ b/ministack/services/eks.py@@ -28,6 +28,7 @@ logger = logging.getLogger("eks")REGION = os.environ.get("MINISTACK_REGION", "us-east-1")EKS_K3S_IMAGE = os.environ.get("EKS_K3S_IMAGE", "rancher/k3s:v1.31.4-k3s1")EKS_BASE_PORT = int(os.environ.get("EKS_BASE_PORT", "16443"))+DOCKER_NETWORK = os.environ.get("DOCKER_NETWORK", "")try:docker_lib = importlib.import_module("docker")@@ -130,6 +131,8 @@ def _get_docker():def _get_ministack_network(client):"""Detect the Docker network MiniStack is running on."""+ if DOCKER_NETWORK:+ return DOCKER_NETWORKtry:hostname = os.environ.get("HOSTNAME", "")if not hostname:diff --git a/ministack/services/elasticache.py b/ministack/services/elasticache.pyindex 8c0bcc43..788849e8 100644--- a/ministack/services/elasticache.py+++ b/ministack/services/elasticache.py@@ -35,6 +35,7 @@ REGION = os.environ.get("MINISTACK_REGION", "us-east-1")REDIS_DEFAULT_HOST = os.environ.get("REDIS_HOST", "redis")REDIS_DEFAULT_PORT = int(os.environ.get("REDIS_PORT", "6379"))BASE_PORT = int(os.environ.get("ELASTICACHE_BASE_PORT", "16379"))+DOCKER_NETWORK = os.environ.get("DOCKER_NETWORK", "")_clusters = AccountScopedDict()_replication_groups = AccountScopedDict()@@ -246,15 +247,30 @@ def _create_cache_cluster(p):container_port = 11211try:- container = docker_client.containers.run(- image, detach=True,+ run_kwargs = dict(+ image=image, detach=True,ports={f"{container_port}/tcp": host_port},name=f"ministack-elasticache-{cluster_id}",labels={"ministack": "elasticache", "cluster_id": cluster_id},volumes={},)+ if DOCKER_NETWORK:+ run_kwargs["network"] = DOCKER_NETWORK+ container = docker_client.containers.run(**run_kwargs)docker_container_id = container.id- logger.info("ElastiCache: started %s container for %s on port %s", engine, cluster_id, host_port)+ if DOCKER_NETWORK:+ container.reload()+ networks = container.attrs.get("NetworkSettings", {}).get("Networks", {})+ container_ip = networks.get(DOCKER_NETWORK, {}).get("IPAddress", "")+ if container_ip:+ endpoint_host = container_ip+ endpoint_port = container_port+ logger.info("ElastiCache: started %s container for %s at %s:%s (network %s)",+ engine, cluster_id, container_ip, container_port, DOCKER_NETWORK)+ else:+ logger.info("ElastiCache: started %s container for %s on port %s", engine, cluster_id, host_port)+ else:+ logger.info("ElastiCache: started %s container for %s on port %s", engine, cluster_id, host_port)except Exception as e:logger.warning("ElastiCache: Docker failed for %s: %s", cluster_id, e)endpoint_host = REDIS_DEFAULT_HOSTdiff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.pyindex b6f59d52..ab99343c 100644--- a/ministack/services/lambda_svc.py+++ b/ministack/services/lambda_svc.py@@ -52,7 +52,7 @@ logger = logging.getLogger("lambda")REGION = os.environ.get("MINISTACK_REGION", os.environ.get("AWS_DEFAULT_REGION", "us-east-1"))LAMBDA_EXECUTOR = os.environ.get("LAMBDA_EXECUTOR", "local").lower()LAMBDA_DOCKER_VOLUME_MOUNT = os.environ.get("LAMBDA_REMOTE_DOCKER_VOLUME_MOUNT", "")-LAMBDA_DOCKER_NETWORK = os.environ.get("LAMBDA_DOCKER_NETWORK", "")+LAMBDA_DOCKER_NETWORK = os.environ.get("DOCKER_NETWORK", "") or os.environ.get("LAMBDA_DOCKER_NETWORK", "")# LAMBDA_STRICT=1 → AWS-fidelity mode: every invocation must run in Docker via# the AWS RIE image (matching fzonneveld's "docker = docker, no fallbacks"# rule). When set, the warm-worker / local-subprocess fallbacks are disableddiff --git a/ministack/services/rds.py b/ministack/services/rds.pyindex 1fb459bf..7a750198 100644--- a/ministack/services/rds.py+++ b/ministack/services/rds.py@@ -49,6 +49,7 @@ REGION = os.environ.get("MINISTACK_REGION", "us-east-1")BASE_PORT = int(os.environ.get("RDS_BASE_PORT", "15432"))RDS_TMPFS_SIZE = os.environ.get("RDS_TMPFS_SIZE", "256m")RDS_PERSIST = os.environ.get("RDS_PERSIST", "0").lower() in ("1", "true", "yes")+DOCKER_NETWORK = os.environ.get("DOCKER_NETWORK", "")_instances = AccountScopedDict()_clusters = AccountScopedDict()@@ -145,6 +146,10 @@ def _get_ministack_network(docker_client):global _ministack_networkif _ministack_network is not None:return _ministack_network or None+ if DOCKER_NETWORK:+ _ministack_network = DOCKER_NETWORK+ logger.debug("RDS: using DOCKER_NETWORK=%s", DOCKER_NETWORK)+ return DOCKER_NETWORKtry:self_container = docker_client.containers.get(os.environ.get("HOSTNAME", ""))@@ -392,6 +397,8 @@ def _create_db_instance(p):if container_ip:internal_host = container_ipinternal_port = container_port+ endpoint_host = container_ip+ endpoint_port = container_portdef _bg_wait(cip=container_ip, cport=container_port,eng=engine, did=db_id, net=ms_network):if _wait_for_port(cip, cport):diff --git a/tests/conftest.py b/tests/conftest.pyindex 29e91d41..f7017a78 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -42,6 +42,8 @@ _SERIAL_TESTS = {"tests/test_sfn.py::test_sfn_mock_config_throw","tests/test_sfn.py::test_sfn_wait_scale_zero_does_not_timeout_lambda_tasks","tests/test_sfn.py::test_sfn_wait_scale_zero_skips_wait",+ "tests/test_rds_lambda_network.py::test_rds_lambda_network_connectivity",+ "tests/test_elasticache_lambda_network.py::test_elasticache_lambda_network_connectivity",}diff --git a/tests/test_elasticache_lambda_network.py b/tests/test_elasticache_lambda_network.pynew file mode 100644index 00000000..69222c0c--- /dev/null+++ b/tests/test_elasticache_lambda_network.py@@ -0,0 +1,143 @@+"""+E2E test: Lambda containers can reach ElastiCache containers over DOCKER_NETWORK.++Skipped when DOCKER_NETWORK is not set (requires Docker networking).+"""+import io+import json+import os+import time+import zipfile++import pytest++pytestmark = pytest.mark.skipif(+ not os.environ.get("DOCKER_NETWORK"),+ reason="DOCKER_NETWORK not set — skipping network connectivity test",+)++_LAMBDA_ROLE = "arn:aws:iam::000000000000:role/lambda-role"+++def _make_zip(code: str) -> bytes:+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as zf:+ zf.writestr("index.py", code)+ return buf.getvalue()+++def _make_zip_js(code: str) -> bytes:+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as zf:+ zf.writestr("index.js", code)+ return buf.getvalue()+++def test_elasticache_lambda_network_connectivity(ec, lam):+ """Prove that Lambda containers can TCP-connect to an ElastiCache container."""+ cluster_id = "net-test-redis"+ fn_py = "ec-net-test-py"+ fn_js = "ec-net-test-js"++ # 1. Create ElastiCache Redis cluster+ ec.create_cache_cluster(+ CacheClusterId=cluster_id,+ Engine="redis",+ CacheNodeType="cache.t3.micro",+ NumCacheNodes=1,+ )++ try:+ resp = ec.describe_cache_clusters(CacheClusterId=cluster_id)+ cluster = resp["CacheClusters"][0]+ node = cluster["CacheNodes"][0]+ host = node["Endpoint"]["Address"]+ port = int(node["Endpoint"]["Port"])++ # 2. Endpoint.Address must NOT be localhost when DOCKER_NETWORK is set+ assert host not in ("localhost", "redis"), (+ f"Expected container IP, got '{host}' — DOCKER_NETWORK not working"+ )++ # 3. Wait for Redis container to accept connections+ import socket+ deadline = time.time() + 60+ while time.time() < deadline:+ try:+ with socket.create_connection((host, port), timeout=2):+ break+ except OSError:+ time.sleep(1)+ else:+ pytest.fail(f"ElastiCache container at {host}:{port} not reachable after 60s")++ # 4. Python Lambda — TCP connect to ElastiCache endpoint+ py_code = f"""\+import socket, json+def handler(event, context):+ try:+ s = socket.create_connection(("{host}", {port}), timeout=5)+ s.close()+ return {{"connected": True}}+ except Exception as e:+ return {{"connected": False, "error": str(e)}}+"""+ lam.create_function(+ FunctionName=fn_py,+ Runtime="python3.12",+ Role=_LAMBDA_ROLE,+ Handler="index.handler",+ Code={"ZipFile": _make_zip(py_code)},+ Timeout=15,+ )++ resp = lam.invoke(FunctionName=fn_py, Payload=json.dumps({}))+ result = json.loads(resp["Payload"].read())+ assert result.get("connected") is True, f"Python Lambda failed: {result}"++ # 5. JS Lambda — TCP connect to ElastiCache endpoint+ js_code = f"""\+const net = require("net");+exports.handler = async (event) => {{+ return new Promise((resolve) => {{+ const sock = new net.Socket();+ sock.setTimeout(5000);+ sock.connect({port}, "{host}", () => {{+ sock.destroy();+ resolve({{ connected: true }});+ }});+ sock.on("error", (err) => {{+ sock.destroy();+ resolve({{ connected: false, error: err.message }});+ }});+ sock.on("timeout", () => {{+ sock.destroy();+ resolve({{ connected: false, error: "timeout" }});+ }});+ }});+}};+"""+ lam.create_function(+ FunctionName=fn_js,+ Runtime="nodejs20.x",+ Role=_LAMBDA_ROLE,+ Handler="index.handler",+ Code={"ZipFile": _make_zip_js(js_code)},+ Timeout=15,+ )++ resp = lam.invoke(FunctionName=fn_js, Payload=json.dumps({}))+ result = json.loads(resp["Payload"].read())+ assert result.get("connected") is True, f"JS Lambda failed: {result}"++ finally:+ # 6. Cleanup+ for fn in (fn_py, fn_js):+ try:+ lam.delete_function(FunctionName=fn)+ except Exception:+ pass+ try:+ ec.delete_cache_cluster(CacheClusterId=cluster_id)+ except Exception:+ passdiff --git a/tests/test_rds_lambda_network.py b/tests/test_rds_lambda_network.pynew file mode 100644index 00000000..ad55d942--- /dev/null+++ b/tests/test_rds_lambda_network.py@@ -0,0 +1,157 @@+"""+E2E test: Lambda containers can reach RDS containers over DOCKER_NETWORK.++Skipped when DOCKER_NETWORK is not set (requires Docker networking).+"""+import io+import json+import os+import time+import zipfile++import pytest++pytestmark = pytest.mark.skipif(+ not os.environ.get("DOCKER_NETWORK"),+ reason="DOCKER_NETWORK not set — skipping network connectivity test",+)++_LAMBDA_ROLE = "arn:aws:iam::000000000000:role/lambda-role"+++def _make_zip(code: str) -> bytes:+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as zf:+ zf.writestr("index.py", code)+ return buf.getvalue()+++def _make_zip_js(code: str) -> bytes:+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as zf:+ zf.writestr("index.js", code)+ return buf.getvalue()+++def _wait_for_rds(rds_client, db_id, timeout=120):+ """Poll DescribeDBInstances until the instance is available."""+ deadline = time.time() + timeout+ while time.time() < deadline:+ resp = rds_client.describe_db_instances(DBInstanceIdentifier=db_id)+ inst = resp["DBInstances"][0]+ if inst["DBInstanceStatus"] == "available":+ return inst+ time.sleep(2)+ raise TimeoutError(f"RDS instance {db_id} not available after {timeout}s")+++def test_rds_lambda_network_connectivity(rds, lam):+ """Prove that Lambda containers can TCP-connect to an RDS container."""+ db_id = "net-test-pg"+ fn_py = "rds-net-test-py"+ fn_js = "rds-net-test-js"++ # 1. Create RDS Postgres instance+ rds.create_db_instance(+ DBInstanceIdentifier=db_id,+ DBInstanceClass="db.t3.micro",+ Engine="postgres",+ MasterUsername="admin",+ MasterUserPassword="password123",+ )++ try:+ inst = _wait_for_rds(rds, db_id)+ endpoint = inst["Endpoint"]+ host = endpoint["Address"]+ port = int(endpoint["Port"])++ # 2. Endpoint.Address must NOT be localhost when DOCKER_NETWORK is set+ assert host != "localhost", (+ f"Expected container IP, got 'localhost' — DOCKER_NETWORK not working"+ )++ # 3. Wait for the Postgres container to accept connections+ import socket+ deadline = time.time() + 60+ while time.time() < deadline:+ try:+ with socket.create_connection((host, port), timeout=2):+ break+ except OSError:+ time.sleep(1)+ else:+ pytest.fail(f"RDS container at {host}:{port} not reachable after 60s")++ # 4. Python Lambda — TCP connect to RDS endpoint+ py_code = f"""\+import socket, json+def handler(event, context):+ try:+ s = socket.create_connection(("{host}", {port}), timeout=5)+ s.close()+ return {{"connected": True}}+ except Exception as e:+ return {{"connected": False, "error": str(e)}}+"""+ lam.create_function(+ FunctionName=fn_py,+ Runtime="python3.12",+ Role=_LAMBDA_ROLE,+ Handler="index.handler",+ Code={"ZipFile": _make_zip(py_code)},+ Timeout=15,+ )++ resp = lam.invoke(FunctionName=fn_py, Payload=json.dumps({}))+ result = json.loads(resp["Payload"].read())+ assert result.get("connected") is True, f"Python Lambda failed: {result}"++ # 5. JS Lambda — TCP connect to RDS endpoint+ js_code = f"""\+const net = require("net");+exports.handler = async (event) => {{+ return new Promise((resolve) => {{+ const sock = new net.Socket();+ sock.setTimeout(5000);+ sock.connect({port}, "{host}", () => {{+ sock.destroy();+ resolve({{ connected: true }});+ }});+ sock.on("error", (err) => {{+ sock.destroy();+ resolve({{ connected: false, error: err.message }});+ }});+ sock.on("timeout", () => {{+ sock.destroy();+ resolve({{ connected: false, error: "timeout" }});+ }});+ }});+}};+"""+ lam.create_function(+ FunctionName=fn_js,+ Runtime="nodejs20.x",+ Role=_LAMBDA_ROLE,+ Handler="index.handler",+ Code={"ZipFile": _make_zip_js(js_code)},+ Timeout=15,+ )++ resp = lam.invoke(FunctionName=fn_js, Payload=json.dumps({}))+ result = json.loads(resp["Payload"].read())+ assert result.get("connected") is True, f"JS Lambda failed: {result}"++ finally:+ # 6. Cleanup+ for fn in (fn_py, fn_js):+ try:+ lam.delete_function(FunctionName=fn)+ except Exception:+ pass+ try:+ rds.delete_db_instance(+ DBInstanceIdentifier=db_id, SkipFinalSnapshot=True+ )+ except Exception:+ pass