diff --git a/docs/services/ecs.md b/docs/services/ecs.md
index 969448bdc6..a1de816cda 100644
--- a/docs/services/ecs.md
+++ b/docs/services/ecs.md
@@ -413,6 +413,13 @@ existing provider counts; tasks from a previous deployment do not cover the new
With no launch type, no strategy and no cluster default, a task keeps Floci's `FARGATE` default: a
local cluster has no container instances, so an EC2 default would have nowhere to place it.
+A `REPLICA` service task placed on the `EC2` launch type, or on a capacity provider other than
+`FARGATE` and `FARGATE_SPOT`, runs on an `ACTIVE` container instance of the cluster: the one
+running the fewest tasks, among the instances registered for that capacity provider when any are,
+otherwise among those registered for none. `DescribeTasks` then reports its
+`containerInstanceArn`. A cluster with no container instance to offer still runs the task, without
+one, where AWS would leave it unplaced. Placement constraints and strategies are not evaluated.
+
#### Task metadata endpoint
Floci serves the [task metadata endpoint version
@@ -559,6 +566,17 @@ Known differences from AWS:
and rolls the running tasks: a replacement on the new deployment normally starts first, then
the task from the previous deployment is drained one reconciler tick later. The
`deployments` list still reports a single `PRIMARY` throughout.
+- A task of a service with `loadBalancers` that runs on a container instance is registered in a
+ target group of target type `instance` as ECS registers it on AWS: the container instance's
+ `ec2InstanceId` on the container's host port. The load balancer and its health checks reach
+ that instance port at the task's container. When another task on the same instance already holds
+ the host port, as when Floci runs in Docker and publishes no host ports so the tasks share a
+ container port, the target gets a port from the ECS agent's dynamic range (32768 to 60999)
+ instead, and `networkBindings` keeps reporting the published port. The container's other
+ published host ports are taken on the instance too where free, so a target group health check on
+ one of them reaches the container. The task holds these ports until it is `STOPPED`, through its
+ deregistration delay, so a replacement on the same instance gets other ones. An `ip` target
+ group, or a task with no container instance, gets the container's own address.
- A rolling deployment of a service with `loadBalancers` stops a stale task only once every
replacement's targets report `healthy`. A replacement that never turns healthy holds the
deployment.
@@ -786,6 +804,12 @@ re-registered `containerInstanceArn` all round-trip. The agent version is report
`agentVersion`. An instance also reports `registeredAt` and a `version` counter that each state
change increments.
+The container instance's `ec2InstanceId` is the `instanceId` of the `instanceIdentityDocument` the
+agent registers with, so it names the EC2 instance the agent runs on, as on AWS. A registration
+without a document gets a generated `i-floci-...` id; one whose document is not JSON or names no
+`instanceId` fails with `InvalidParameterException`. Floci does not check
+`instanceIdentityDocumentSignature`.
+
`DeregisterContainerInstance` leaves the instance in the cluster as `INACTIVE` rather than
dropping it, so a later `DescribeContainerInstances` still answers for it, as on AWS. A cluster's
`registeredContainerInstancesCount` counts only the `ACTIVE` and `DRAINING` instances.
diff --git a/docs/services/elb.md b/docs/services/elb.md
index c4f70825cd..61a9981a55 100644
--- a/docs/services/elb.md
+++ b/docs/services/elb.md
@@ -145,7 +145,7 @@ Gateway Load Balancer listeners require omitted `Port` and `Protocol` fields on
- EC2 refuses deletion of subnets and VPCs still referenced by load balancers with `DependencyViolation`. These account- and region-scoped dependencies follow persisted load balancer state; changing subnets or deleting the load balancer releases its old references. A CloudFormation update that names other subnets in `Subnets` or `SubnetMappings` moves the load balancer the way `SetSubnets` does, and a rolled-back update moves it back. An independent target group does not prevent subnet or VPC deletion.
- HTTP listener sockets are preserved when listener actions change and are restarted only when socket-level settings such as port change.
- Gateway listeners require `Protocol` and `Port` to be omitted on create and modify. Their control-plane response reports `GENEVE` without a port. CloudFormation preserves omitted gateway listener settings on create and update; other load balancer types retain their existing `HTTP` and port 80 defaults.
-- Instance targets are resolved through EC2 instance private addresses so local load balancer traffic can reach containers.
+- Instance targets are resolved through EC2 instance private addresses so local load balancer traffic can reach containers. An instance port that an ECS task on that container instance publishes resolves to the task's container instead, which is how an ECS service in `bridge` or `host` network mode serves an `instance` target group (see [ECS](ecs.md)).
- Target health starts in `initial` state with reason `Elb.RegistrationInProgress` and is updated by Floci's health checker when monitoring is active.
- A newly registered Application Load Balancer target (HTTP/HTTPS target group or Lambda target) becomes healthy after its first successful check. Network and Gateway target groups retain `HealthyThresholdCount` for initial admission. The threshold applies to every group when recovering from `unhealthy`.
- Health checks probe the target group's `HealthCheckPort` when it is a port number, and each target's own port when it is `traffic-port` (the default).
diff --git a/src/main/java/io/floci/aws/services/ec2/Ec2InstancePorts.java b/src/main/java/io/floci/aws/services/ec2/Ec2InstancePorts.java
new file mode 100644
index 0000000000..f02a6ea99b
--- /dev/null
+++ b/src/main/java/io/floci/aws/services/ec2/Ec2InstancePorts.java
@@ -0,0 +1,60 @@
+package io.floci.aws.services.ec2;
+
+import io.floci.aws.core.common.Resettable;
+import jakarta.enterprise.context.ApplicationScoped;
+
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * The host ports of an EC2 instance that something other than the instance's own container
+ * serves. An ECS task in {@code bridge} or {@code host} network mode is placed on a container
+ * instance and is addressed, as on AWS, by that instance's id and the host port it publishes,
+ * but its containers run beside the instance rather than inside it. ECS records here where such a
+ * port is actually reachable, so an ELBv2 {@code instance} target {@code i-...:port} reaches the
+ * task the way AWS forwards it to the instance's primary address on that port.
+ *
+ *
Memory only: the tasks that publish these ports do not survive a restart either.
+ */
+@ApplicationScoped
+public class Ec2InstancePorts implements Resettable {
+
+ /** Where a published instance port is reachable from the Floci process. */
+ public record Endpoint(String host, int port) {}
+
+ private record Key(String accountId, String instanceId, int port) {}
+
+ private final Map endpoints = new ConcurrentHashMap<>();
+
+ /**
+ * Records that {@code instanceId}'s {@code port} is served at {@code endpoint}.
+ *
+ * @return false, recording nothing, when another endpoint already holds that port
+ */
+ public boolean bind(String accountId, String instanceId, int port, Endpoint endpoint) {
+ Endpoint existing = endpoints.putIfAbsent(new Key(accountId, instanceId, port), endpoint);
+ return existing == null || existing.equals(endpoint);
+ }
+
+ /** Releases {@code instanceId}'s {@code port} if {@code endpoint} still holds it. */
+ public void release(String accountId, String instanceId, int port, Endpoint endpoint) {
+ endpoints.remove(new Key(accountId, instanceId, port), endpoint);
+ }
+
+ public boolean isBound(String accountId, String instanceId, int port) {
+ return endpoints.containsKey(new Key(accountId, instanceId, port));
+ }
+
+ public Optional find(String accountId, String instanceId, int port) {
+ if (accountId == null || instanceId == null) {
+ return Optional.empty();
+ }
+ return Optional.ofNullable(endpoints.get(new Key(accountId, instanceId, port)));
+ }
+
+ @Override
+ public void clear() {
+ endpoints.clear();
+ }
+}
diff --git a/src/main/java/io/floci/aws/services/ecs/EcsLoadBalancerRegistrar.java b/src/main/java/io/floci/aws/services/ecs/EcsLoadBalancerRegistrar.java
index 523fe38499..742944edf6 100644
--- a/src/main/java/io/floci/aws/services/ecs/EcsLoadBalancerRegistrar.java
+++ b/src/main/java/io/floci/aws/services/ecs/EcsLoadBalancerRegistrar.java
@@ -1,9 +1,11 @@
package io.floci.aws.services.ecs;
import com.fasterxml.jackson.core.type.TypeReference;
+import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageFactory;
+import io.floci.aws.services.ec2.Ec2InstancePorts;
import io.floci.aws.services.ecs.container.EcsContainerManager;
import io.floci.aws.services.ecs.model.Container;
import io.floci.aws.services.ecs.model.EcsLoadBalancer;
@@ -14,6 +16,7 @@ import io.floci.aws.services.ecs.model.EcsTaskAddress;
import io.floci.aws.services.ecs.model.NetworkBinding;
import io.floci.aws.services.elbv2.ElbV2Service;
import io.floci.aws.services.elbv2.model.TargetDescription;
+import io.floci.aws.services.elbv2.model.TargetGroup;
import io.floci.aws.services.elbv2.model.TargetHealth;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -28,7 +31,8 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
-import java.util.function.BiConsumer;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicReference;
/**
* Bridges ECS services to ELBv2: when an ECS service declares a {@code loadBalancers}
@@ -42,17 +46,27 @@ import java.util.function.BiConsumer;
public class EcsLoadBalancerRegistrar {
private static final Logger LOG = Logger.getLogger(EcsLoadBalancerRegistrar.class);
+ // The ECS agent's default range for dynamic host ports on Amazon Linux.
+ private static final int EPHEMERAL_PORT_MIN = 32768;
+ private static final int EPHEMERAL_PORT_MAX = 60999;
private final ElbV2Service elbV2Service;
private final EcsContainerManager containerManager;
// taskArn → the targets registered for it, persisted so they can be released after a restart
private final AccountAwareStorageBackend ledger;
+ private final Ec2InstancePorts instancePorts;
+ // taskArn → the container instance host ports the task holds until it stops, memory-only like the
+ // task itself. Each list is immutable and replaced through compute(), which is atomic per task.
+ private final Map> heldInstancePorts = new ConcurrentHashMap<>();
+
+ private record InstancePort(String accountId, String instanceId, int port, Ec2InstancePorts.Endpoint endpoint) {}
@Inject
public EcsLoadBalancerRegistrar(ElbV2Service elbV2Service, EcsContainerManager containerManager,
- StorageFactory storageFactory) {
+ StorageFactory storageFactory, Ec2InstancePorts instancePorts) {
this.elbV2Service = elbV2Service;
this.containerManager = containerManager;
+ this.instancePorts = instancePorts;
this.ledger = storageFactory.create("ecs", "ecs-registered-targets.json",
new TypeReference