You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Amazon Web Server开机时自动运行Shell脚本?

解决AWS EC2开机自动执行Start.sh脚本的问题

Hey there, let's work through why your Start.sh script isn't auto-running on EC2 boot via User Data. I've tackled similar boot automation issues on EC2 before, so here are the key checks and fixes to get this working:

1. First, check if User Data is actually running

EC2 User Data logs everything to two key files—start by checking these to see where things might be failing:

cat /var/log/cloud-init.log
cat /var/log/cloud-init-output.log

These logs will tell you if the User Data script ran, if it hit errors (like missing paths or permission issues), or if it skipped execution entirely.

2. Fix path & permission issues in your User Data

Your current script runs as root, which can cause problems with the ec2-user home directory permissions and environment. Here's a revised version that addresses these:

#!/bin/bash
# Define the script path clearly
SCRIPT_PATH="/home/ec2-user/app_name/Start.sh"
LOG_PATH="/home/ec2-user/app_name/boot_log.txt"

# Check if the script exists first
if [ -f "$SCRIPT_PATH" ]; then
    # Give the script execute permissions (just in case)
    chmod +x "$SCRIPT_PATH"
    # Run the script as ec2-user (preserves their environment variables)
    su - ec2-user -c "$SCRIPT_PATH"
    echo "Successfully ran Start.sh at $(date)" >> "$LOG_PATH"
else
    echo "ERROR: Start.sh not found at $SCRIPT_PATH on $(date)" >> "$LOG_PATH"
fi
  • Using su - ec2-user ensures the script runs with the correct user context (many apps rely on ec2-user's environment, not root's)
  • Adding checks and logs makes it way easier to debug later

3. Verify the script works manually first

Before relying on User Data, log into your EC2 instance as ec2-user and run:

cd /home/ec2-user/app_name/
sh Start.sh

If this fails, fix the script itself first—check for missing dependencies, port conflicts, or hardcoded paths that only work when you're logged in.

4. Make User Data run on every boot (optional)

By default, Amazon Linux 2/2023 runs User Data only once on the first boot. If you want it to run every time the server restarts:

  1. Edit the cloud-init config file:
    sudo nano /etc/cloud/cloud.cfg
    
  2. Find the line that looks like:
    - [user-scripts, once]
    
  3. Change once to always:
    - [user-scripts, always]
    
  4. Save the file and restart the cloud-init service:
    sudo systemctl restart cloud-init
    

内容的提问来源于stack exchange,提问作者Santiago Diaz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:25:19