Question

connect() failed (111: Connection refused) while connecting to upstream

I have a One-Click MySQL/phpMyAdmin Droplet, I have stopped Apache2 from listening on port 80, I’m trying to deploy my Django project using Gunicorn and Nginx. Here is my Django settings.py file

import os
import datetime
from datetime import timedelta

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

DEBUG = True

ALLOWED_HOSTS = ['0.0.0.0', 'MyDropletIP']

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'corsheaders',
    # 'django_seed',
    'rest_framework'
]


MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]


ROOT_URLCONF = ''

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],  # os.path.join(SETTINGS_PATH, 'templates')
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = ''

CORS_ORIGIN_ALLOW_ALL = True

CORS_ALLOW_METHODS = [
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
]

CORS_ALLOW_HEADERS = [
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
]


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': '',
        'HOST': "",
        'USER': "",
        'PASSWORD': ,
        'PORT': "3306",
    }
    
}

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

REST_FRAMEWORK = {

    'DEFAULT_PAGINATION_CLASS': 'news.serialiazers.PageNumberPagination',
    'PAGE_SIZE': 10,
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',

    ),
    # 'PAGE_COUNT':'page.paginator.count'
}


AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend',  # this is default
    'guardian.backends.ObjectPermissionBackend',
)

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Africa/Cairo'

USE_I18N = True

USE_L10N = False

USE_TZ = False


STATIC_ROOT = os.path.join(BASE_DIR, "static/")
STATIC_URL = '/static/'
AUTH_USER_MODEL = 'users.User'

Here is my Gunicorn service file

[Unit]
Description=gunicorn daemon
After=network.target

[Service]
User=my_user
Group=www-data
WorkingDirectory=/home/my_user/my_project
ExecStart=/home/my_user/.local/bin/gunicorn --timeout 30 workers 15 --bind 0.0.0.0:8000 my_project.wsgi:application
[Install]
WantedBy=multi-user.target

Gunicorn socket file

[Unit]
Description=gunicorn socket

[Socket]
ListenStream=/run/gunicorn.sock
SocketUser=www-data

[Install]
WantedBy=sockets.service

Nginx configuraion in /etc/nginx/sites-available/my_project_nginx.conf

upstream django {
server 0.0.0.0:8000
fail_timeout=15;
}
server listen 80;
server_name my_droplet_ip;
charset utf-8;
client_max_body_size 4G;
location /media {
alias /home/my_user/my_project/media;
}
location /static {
alias /home/my_user/my_project/static;
}
location / {
uwsgi_pass django;
include /home/my_user/my_project/uswgi_params;
proxy_set_header Host $host;
proxy_pass http://my_droplet_ip:8000;
proxy_set_header XForwardedHost $server_name;
proxy_set_header XReal-IP $remote_addr;
add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"';
}
}

Error in /var/log/nginx/error.log

connect() failed (111: Connection refused) while connecting to upstream, client: client_ip, server: my_droplet_ip, request: "GET /favicon.ico HTTP/1.1", upstream: "http://my_droplet_ip:8080/favicon.ico", host: "my_droplet_ip", referrer: "http://my_droplet_ip"

Output of netstat -l

Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State      
tcp        0      0 0.0.0.0:mysql           0.0.0.0:*               LISTEN     
tcp        0      0 0.0.0.0:http            0.0.0.0:*               LISTEN     
tcp        0      0 localhost:domain        0.0.0.0:*               LISTEN     
tcp        0      0 0.0.0.0:ssh             0.0.0.0:*               LISTEN     
tcp        0      0 0.0.0.0:8000            0.0.0.0:*               LISTEN     
tcp6       0      0 [::]:http               [::]:*                  LISTEN     
tcp6       0      0 [::]:ssh                [::]:*                  LISTEN     
udp        0      0 localhost:domain        0.0.0.0:*                          
raw6       0      0 [::]:ipv6-icmp          [::]:*                  7          
Active UNIX domain sockets (only servers)
Proto RefCnt Flags       Type       State         I-Node   Path
unix  2      [ ACC ]     SEQPACKET  LISTENING     11724    /run/udev/control
unix  2      [ ACC ]     STREAM     LISTENING     1072359  /run/user/1000/systemd/private
unix  2      [ ACC ]     STREAM     LISTENING     1072363  /run/user/1000/gnupg/S.dirmngr
unix  2      [ ACC ]     STREAM     LISTENING     1072364  /run/user/1000/snapd-session-agent.socket
unix  2      [ ACC ]     STREAM     LISTENING     1072365  /run/user/1000/gnupg/S.gpg-agent.browser
unix  2      [ ACC ]     STREAM     LISTENING     1072366  /run/user/1000/gnupg/S.gpg-agent.extra
unix  2      [ ACC ]     STREAM     LISTENING     1072367  /run/user/1000/gnupg/S.gpg-agent.ssh
unix  2      [ ACC ]     STREAM     LISTENING     1072368  /run/user/1000/gnupg/S.gpg-agent
unix  2      [ ACC ]     STREAM     LISTENING     11720    /run/lvm/lvmetad.socket
unix  2      [ ACC ]     STREAM     LISTENING     11731    /run/systemd/journal/stdout
unix  2      [ ACC ]     STREAM     LISTENING     1045169  /run/gunicorn.sock
unix  2      [ ACC ]     STREAM     LISTENING     12094    /run/lvm/lvmpolld.socket
unix  2      [ ACC ]     STREAM     LISTENING     172172   /var/run/supervisor.sock.30741
unix  2      [ ACC ]     STREAM     LISTENING     16301    /run/acpid.socket
unix  2      [ ACC ]     STREAM     LISTENING     16357    @ISCSIADM_ABSTRACT_NAMESPACE
unix  2      [ ACC ]     STREAM     LISTENING     16345    /var/lib/lxd/unix.socket
unix  2      [ ACC ]     STREAM     LISTENING     16323    /var/run/dbus/system_bus_socket
unix  2      [ ACC ]     STREAM     LISTENING     16333    /run/uuidd/request
unix  2      [ ACC ]     STREAM     LISTENING     86135    /run/snapd.socket
unix  2      [ ACC ]     STREAM     LISTENING     86136    /run/snapd-snap.socket
unix  2      [ ACC ]     STREAM     LISTENING     19112    /var/run/mysqld/mysqld.sock
unix  2      [ ACC ]     STREAM     LISTENING     74383    /run/systemd/private

output of ufw status

Status: active

To Action From


22/tcp LIMIT Anywhere
443/tcp ALLOW Anywhere
80/tcp ALLOW Anywhere
3306 ALLOW Anywhere
Nginx HTTP ALLOW Anywhere
8000/tcp ALLOW Anywhere
8001/tcp ALLOW Anywhere
8080 ALLOW Anywhere
22/tcp (v6) LIMIT Anywhere (v6)
443/tcp (v6) ALLOW Anywhere (v6)
80/tcp (v6) ALLOW Anywhere (v6)
3306 (v6) ALLOW Anywhere (v6)
Nginx HTTP (v6) ALLOW Anywhere (v6)
8000/tcp (v6) ALLOW Anywhere (v6)
8001/tcp (v6) ALLOW Anywhere (v6)
8080 (v6) ALLOW Anywhere (v6)


Submit an answer


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

KFSys
Site Moderator
Site Moderator badge
November 9, 2020
Accepted Answer

Hello @abdelnasserahmed96,

Usually the

connect() failed (111: Connection refused) while connecting to upstream

error is related to an error with your Application/configuration rather than Nginx.

Try to remove http:// from the proxy_pass in the Nginx configuration. The reason is that Gunicorn is listening on a unix socket (the --bind argument). Then Nginx should forward traffic to this socket. http:// stands for a TCP socket in a regular IP:PORT, which is not your case.

Regards, KFSys

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.