# 🚀 Automating Nginx & Custom Scripts with Cronjobs on EC2 Ubuntu

Modern server management in the cloud demands repeatability and automation. As part of my DevOps skill development, I successfully set up an AWS EC2 instance, deployed an Nginx web server, automated server maintenance using cronjobs, and built custom shell scripts for scheduled tasks. This blog details my hands-on journey, professional approach, and practical learnings

#### 🟢 . **Cron Time Format Explanation**

```powershell
# ┌───────────── minute (0 - 59)
# │ ┌───────────── hour (0 - 23)
# │ │ ┌───────────── day of month (1 - 31)
# │ │ │ ┌───────────── month (1 - 12)
# │ │ │ │ ┌───────────── day of week (0 - 6) (Sunday=0 or 7)
# │ │ │ │ │
# │ │ │ │ │
# * * * * * <command-to-execute>
```

### 🔧 Useful Crontab Commands for Linux Automation

| Command | Description |
| --- | --- |
| `crontab -e` | Edit the current user’s crontab file to schedule tasks |
| `crontab -l` | List/show all scheduled cron jobs for the current user |
| `crontab -r` | Remove the current user’s crontab (all jobs) |
| `crontab -u <user> -l` | View cron jobs of a specific user (run as root) |
| `sudo service cron status` | Check the status of the cron service |
| `sudo service cron start` | Start the cron service (if stopped) |
| `sudo service cron stop` | Stop the cron service |
| `sudo service cron restart` | Restart the cron service |

## 📝 **Task Objective**

**Goal:**

*   Deploy and manage an AWS EC2 (Ubuntu) instance
    
*   Automate Nginx server installation and daily management
    
*   Schedule Nginx “**restart” at 7 AM** daily
    
*   Run a custom shell script **every day at 2 AM** using cronjobs
    
*   Achieve all objectives with pure automation—no manual intervention
    

## 1️⃣ **Launching an EC2 Ubuntu Instance**

*   **OS:** Ubuntu 22.04 LTS
    
*   **Instance Type:** t2.micro (Free Tier eligible)
    
*   **Key Pair:** Secure EC2 access using `.pem` SSH key
    
*   **Security Group:**
    
    *   Allow port **22** (SSH) for terminal access
        
    *   Allow port **80** (HTTP) for web access (Nginx)
        

**Connect to your instance:**

```plaintext
ssh -i "your-key.pem" ubuntu@your-ec2-public-ip
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1753009917339/7562bc0c-d54c-4916-80e6-0d58902c4898.png align="center")

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1753009928937/5639f18c-f8f0-451d-8666-1d65b7566fb8.png align="center")

### 🧩 Step 2: Manually Installing and Verifying Nginx Web Server on EC2

After launching the EC2 instance, the next step was to **manually install the Nginx web server**. This helps in quickly testing server availability and basic connectivity.

#### ⚙️ Commands Used for Nginx Installation

Below are the individual commands I executed one by one:

```powershell
# Step 1: Update package list
sudo apt update

# Step 2: Install Nginx
sudo apt install nginx -y

# Step 3: Enable Nginx to start on boot
sudo systemctl enable nginx

# Step 4: Start Nginx service
sudo systemctl start nginx

# Step 5: Check Nginx service status
sudo systemctl status nginx
```

#### ✅ How I Verified the Installation

Once the installation was successful:

*   I **copied the public IPv4 address** of the EC2 instance.
    
*   Opened it in a web browser like this:
    

```plaintext
http://<your-ec2-public-ip>
```

If everything is set up correctly, the **default Nginx welcome page** appears with the message:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1753010604429/214910ce-b321-4fbb-a11b-b2bfc85ed0fc.png align="center")

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1753010121776/8555016d-37ef-4004-b62b-98b6e7ef08a7.png align="center")

## 🚀 Step 3: Creating the Shell Script (`myscript.sh`)

After setting up Nginx, the next part of the task was to create a shell script that performs a simple operation appending a timestamped log to a file every time it runs.

### 🔧 1. Open a new script file using Vim

First, I created a new shell script using the Vim editor by running the following command:

```powershell
vim myscript.sh
```

This opened the Vim editor where I could write my script.

* * *

### 📝 2. Script Content

Inside the `myscript.sh` file, I added the following lines of code:

```powershell
#!/bin/bash
echo "Script ran at $(date)" >> /home/ubuntu/myscript.log
```

📌 This script appends the current date and time to a log file named `myscript.log` located in the `/home/ubuntu/` directory. Every time the script runs, a new entry is added to the log, which is useful for tracking execution.

* * *

### 💾 3. Save and Exit the File

To save and exit in Vim:

*   Press `Esc`
    
*   Then type `:wq` and hit `Enter`
    

This saves the script and brings you back to the terminal.

* * *

### ✅ 4. Make the Script Executable

Before we can run the script manually or via a cron job, we need to give it executable permissions. I used the following command:

```powershell
chmod +x myscript.sh
```

Now the script is ready to be run manually or scheduled using cron in the next step.

### Fixing Permission Error (optional step)

When I tried to run `myscript.sh`, I got a **"Permission denied"** error because the log file `/home/ubuntu/myscript.log` was owned by the **root** user. This prevented the script from writing to the file.

To fix this issue, I followed these steps:

1.  Noticed the permission error related to `myscript.log`.
    
2.  Checked the file ownership it was owned by **root**.
    
3.  Changed the ownership from `root` to the `ubuntu` user using `chown`.
    
4.  After that, the script executed successfully and started logging entries as expected.
    

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1753013400523/14c211e5-f3ca-409d-a28a-ec45556da693.png align="center")

### 🕓 Step 4: Automating Tasks Using Cron Jobs

One of the most powerful aspects of Linux-based systems is automation — and **Cron Jobs** are the go-to solution for scheduling repetitive system-level tasks. In this step, I utilized cron to automate essential backend processes on my EC2 instance.

* * *

### ✅ Automation Goals for This Project

As per the task requirements, I needed to automate the following:

🔁 **Restart the Nginx service** daily at **7:00 AM**  
📜 **Run a custom shell script** daily at **2:00 AM**  
🧪 **(Optional)** Test cron functionality by logging timestamps **every minute**

* * *

### 🛠️ Editing the Crontab

To configure these cron jobs, I used the `crontab` utility:

```powershell
crontab -e
```

📝 On first run, it prompts to choose an editor — I went with **vim**, since I’m already comfortable using it.

* * *

### 📄 Cron Job Entries I Added

```powershell
# Restart Nginx at 7 AM daily
0 7 * * * /bin/systemctl restart nginx

# Run your script at 2 AM daily
0 2 * * * /home/ubuntu/myscript.sh

# Test Cron (runs every minute) - for debugging only
* * * * * echo "Cron Working ✅ $(date)" >> /home/ubuntu/testcron.log
```

* * *

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1753010863512/3e3a87f6-6072-41db-855e-2cf56c66924a.png align="center")

### 📌 What Each Cron Job Does

| Time | Task Description | Command Executed |
| --- | --- | --- |
| `0 7 * * *` | Daily at 7:00 AM | Restarts the **Nginx** service via `systemctl` |
| `0 2 * * *` | Daily at 2:00 AM | Executes the **custom script** `myscript.sh` |
| `* * * * *` | Every minute (for testing/debug only) | Appends a timestamp to `/home/ubuntu/testcron.log` |

* * *

### 🔍 Verifying If Cron Jobs Are Working

To check the **test cron job**, I opened the log file:

```powershell
cat /home/ubuntu/testcron.log
```

If successful, you’ll see output like this — a new line for every minute passed:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1753010896304/4436dc34-6fe0-4e02-82f2-fe85ba8e7815.png align="center")

## 🔍 Viewing Scheduled Cron Jobs Using `crontab -l`

When working with **automated scripts** or scheduled tasks in Linux, cron jobs become your best friend. But what if you want to **check which cron jobs are already scheduled**? That’s where the simple yet powerful command comes in

### ✅ Command:

```powershell
crontab -l
```

### 📌 What it does:

This command **lists all the cron jobs** currently scheduled for the **logged-in user**.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1753011074044/fc3199e8-d059-4981-b33e-d2184d9a0dcf.png align="center")

### 📊 Confirming Cron Daemon Status

To ensure that the cron service is running correctly, I checked its status using:

```powershell
sudo systemctl status cron
```

✅ The output showed:

*   **Status: Active (running)**
    
*   Logs confirming each cron job run
    

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1753011251249/00d17e54-62af-4b2a-a8ea-0e3dd9359688.png align="center")

**✅ Conclusion:-**

In this task, I demonstrated how to automate tasks using `cron jobs` on an Ubuntu server. Starting from manually installing Nginx, writing a shell script using `vim`, assigning it to `crontab`, and verifying the scheduled jobs ,this step-by-step guide helps streamline repetitive processes efficiently. Crontab is a powerful Linux utility to schedule scripts, system maintenance, backups, and more ultimately enhancing productivity and automation.

## **👨‍💻 About the Author**

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1751797710818/123a7231-3dca-4273-ad68-7bd026f69b95.png?auto=compress,format&format=webp&auto=compress,format&format=webp&auto=compress,format&format=webp align="left")

This series isn't just about using AWS; it's about **mastering the core services that power modern cloud infrastructure**.

* * *

### 📬 Let's Stay Connected

*   📧 **Email**: [**gujjarapurv181@gmail.com**](mailto:gujjarapurv181@gmail.com)
    
*   🐙 **GitHub**: [**github.com/ApurvGujjar07**](http://github.com/ApurvGujjar07)
    
*   💼 **LinkedIn**: [**linkedin.com/in/apurv-gujjar**](http://linkedin.com/in/apurv-gujjar)
