Thursday, March 17, 2022

[SOLVED] Cannot access Django server on EC2 instance

Issue

I created an EC2 instance. Installed Python 3.4 on it and then installed Django 1.10.6 on it. I was trying to develop my first django application

I started django server.

python manage.py runserver

I could not access at http://n.n.n.n:8000. I get a ERR_CONNECTION_REFUSED error.

I went back to the EC2 instance and added the protocol/port to the security group. This is how it looks after I add the port/proptocol

Custom TCP Rule  TCP  8000  0.0.0.0/0
Custom TCP Rule  TCP  8000  ::/0

It did not work. I even added a rule to allow all traffic from anywhere. It still did not work.

However, if I start django server the following way

python manage.py runserver 0.0.0.0:8000

I get the following error:

DisallowedHost at /
Invalid HTTP_HOST header: 'n.n.n.n:8000'. You may need to add 'n.n.n.n' to ALLOWED_HOSTS.

If tried adding the IP to ProjectName/settings.py,

ALLOWED_HOSTS = ['n.n.n.n'] #Make sure your host IP is a string

I get the ERR_CONNECTION_REFUSED error

I can ping the IP. I can ssh (there is rule to allow ssh). Does not look like there is a firewall.

$ sudo service iptables status
iptables: Firewall is not running.

Why am I not able access http/django server?

Thanks


Solution

Actually, I must not have started the server right, when I added the host to the ProjectName/settings.py file. I tried again, and this time it worked.

So looks like

django server started on EC2 instances with the following

python manage.py runserver

may not be accessible from other machines.

django server started with the following

python manage.py runserver 0.0.0.0:8000

would be accessible from the Internet provided the IP address of the host machine is added to the ALLOWED_HOSTS in the ProjectName/settings.py file

ALLOWED_HOSTS = ['n.n.n.n'] #Make sure your host IP is a string

This is all in addition to the entries in the security group



Answered By - user2125853
Answer Checked By - Pedro (WPSolving Volunteer)