Run a python script on AWS EC2 instance

ยท

2 min read

Run a python script on AWS EC2 instance

Photo by Chris Ried on Unsplash

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

  1. Sign in to your AWS account
  2. 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. Screenshot 2022-08-20 185639.png
  3. Now, you should be at the dashboard of the EC2 management console. Click on launch instance. Screenshot 2022-08-20 190119.png
  4. Now, you can configure properties for your EC2 instance. Screenshot 2022-08-20 190517.png

  5. In the Names and tags section, add a name for your EC2 instance

  6. 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.
  7. In the Instance type section, choose according to your needs. I have chosen the t2.micro type as it's free to use.
  8. 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.

Screenshot 2022-08-20 191400.png

  • 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

Screenshot 2022-08-20 191850.png

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.

  1. Select your created instance, and click on connect image.png
  2. Open Git Bash and change directory to where you downloaded your key-pair file (mine was in downloads)
  3. Now run these 2 commands which are shown in your AWS Console image.png
  4. Now you have access to your remote Virtual Machine with Ubuntu installed on it.

Running python script

  1. Run sudo apt-get update to update the package lists
  2. Run sudo apt-get install git to install git
  3. 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.
  4. 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.
  5. Now simply, change directory to where your script is located and run that script using python <your-filename>
ย