s16h
s16h

Reputation: 4855

Stopping AWS ECS Fargate task when docker container stops

Is there a way to have an AWS ECS Fargate task automatically stop when the Docker container stops?

Upvotes: 3

Views: 4702

Answers (3)

Tomasz
Tomasz

Reputation: 1416

It is possible to close context, then ECS fargate task will stop. In my case spring boot apllication class implements CommandLineRunner,. Inside method run you should close context ((ConfigurableApplicationContext) context).close();

@SpringBootApplication
public class YourApplication implements CommandLineRunner {
    
    @Autowired
    private ApplicationContext context;
    @Autowired
    private SynchronizationService synchronizationService;

    public static void main(String[] args) {
        SpringApplication.run(YourApplication.class, args);
    }

    @Override
    public void run(String... args) {
        synchronizationService.runSynchronization();
        ((ConfigurableApplicationContext) context).close();
    }
    
}

My Dockerfile :

FROM amazoncorretto:11.0.19-al2023

COPY target/*.jar app.jar
    
ENTRYPOINT ["sh", "-c", "java -cp app.jar org.springframework.boot.loader.PropertiesLauncher"]

Upvotes: 0

tanvi
tanvi

Reputation: 628

Launch a task, not a service. A service is for long running processes that need to remain running throughout. Your use case requires a task that will exit the container once it's done. Have your Dockerfile make use of the CMD option. Example:

FROM node:6
WORKDIR /usr/local/src/app
COPY . .

# ...

CMD [ "node", "script-name.js" ]

Make sure your script is exiting correctly, and that there are no other processes that started during that time that are running even after your cmd script has terminated, which may be causing your container to stay active for longer.

Upvotes: 4

Brett Green
Brett Green

Reputation: 3765

A docker container should have a CMD script. When that CMD script terminates, the docker container will stop and, as a result, your ECS task should also stop. Note, that if you've launched it as a service of some kind, ECS will launch a replacement task (for example, to keep your web server up in the event of a fault or error)

If your ECS task is not stopping when your container 'stops', then I'd guess your command is pointing at something that never stops (like a BASH shell) and you are launching your main task some other way. This should just 'work' if your container is built in a canonical way.

Upvotes: 2

Related Questions