In this article, we'll be learning how to run a Python script 24*7 on AWS EC2 instance.
Prerequisite
- We'll assume that you have added your python program to your GitHub.
- Have Git Bash installed
Creating an AWS EC2 instance
- Sign in to your AWS account
- In the AWS Console, click on the EC2 service. If you are not able to find, then search for it from the search bar on top.
- Now, you should be at the dashboard of the EC2 management console. Click on launch instance.
Now, you can configure properties for your EC2 instance.
In the Names and tags section, add a name for your EC2 instance
- In the Application and OS Images section, choose whatever fits your best use case. I have chose Ubuntu as it's free and most widely used.
- In the Instance type section, choose according to your needs. I have chosen the t2.micro type as it's free to use.
- In the Key pair section, click on Create new key pair. Enter a key-pair name, and make sure the rest of the settings are same as shown in the image below. Click on Create Key, which will download that file for you.
- Finally, click on Launch instance. This will launch the EC2 instance. You should see a success screen like the one below. Click on View all instances
Connecting to AWS EC2 instance
We have now created our EC2 instance which is up and running. But now, we need to connect to the instance remotely, so that we can access that Virtual Machine.
- Select your created instance, and click on connect
- Open Git Bash and change directory to where you downloaded your key-pair file (mine was in downloads)
- Now run these 2 commands which are shown in your AWS Console
- Now you have access to your remote Virtual Machine with Ubuntu installed on it.
Running python script
- Run
sudo apt-get update
to update the package lists - Run
sudo apt-get install git
to install git - Now that git is installed you can easily access your codebase by cloning your GitHub repo.
Run
git clone <your-repo-git-url>
to clone the repository. - Start a tmux window on EC2 by running
tmux new -s mywindow
. This will ensure that your script runs 24*7, even when you shut down your computer. - Now simply, change directory to where your script is located and run that script using
python <your-filename>
ย