iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📌

How to Automatically Execute Commands After EC2 Instance Reboot

に公開

Steps to Automatically Run Specific Commands After EC2 Instance Reboot

Steps

To automatically run specific commands after an EC2 instance reboot, perform the following steps.

1. Create a Shell Script

First, organize the commands you want to execute into a shell script. For example, create a shell script named start_hellowork.sh.

#!/bin/bash

# Remove existing container
docker rm -f hellowork-scray-app-container

# Move to application directory
cd ~/hellowork_scray_app/

# Build Docker image and run container
docker build -t hellowork_scray-app . && docker run -d -p 5000:5000 --name hellowork-scray-app-container hellowork_scray-app

Save this script in an appropriate location, such as ~/start_hellowork.sh.

2. Grant Execution Permission to the Shell Script

Grant execution permission to the created shell script.

vi ~/start_hellowork.sh
chmod +x ~/start_hellowork.sh

3. Create a systemd Service

Next, create a systemd service to automatically execute this script upon system startup.

Create a file named /etc/systemd/system/hellowork.service and add the following content.

sudo vi /etc/systemd/system/hellowork.service
[Unit]
Description=Start Hellowork Scray App on boot
After=docker.service

[Service]
ExecStart=/home/ec2-user/start_hellowork.sh
Restart=on-failure
User=ec2-user

[Install]
WantedBy=multi-user.target

Here, specify the path of the shell script you created earlier in ExecStart. Specify the user who will run the script in User (e.g., ec2-user).

4. Enable the systemd Service

Enable the created service so that it runs automatically upon system startup.

sudo systemctl daemon-reload
sudo systemctl enable hellowork.service
sudo systemctl start hellowork.service

5. Verify the Service Status

Check if the service is running correctly.

sudo systemctl status hellowork.service

With this, the specified commands will be automatically executed every time the EC2 instance is rebooted.

Discussion