why do i have error "Address already in use"?

22.7k Views Asked by At

i run my flask app, and it works good, but by the time the app is stopped and in my uwsgi log

probably another instance of uWSGI is running on the same address (127.0.0.1:9002).
    bind(): Address already in use [core/socket.c line 764]

when i run touch touch_reload, app is working again. I run anything else on the server which may take the socket.

my conf:

nginx
server {
    listen 80;
    ....
    location / {
       include uwsgi_params;
       uwsgi_pass 127.0.0.1:9001;
    }
    ....
}
server {
    listen 80;
    ....
    location / {
       include uwsgi_params;
       uwsgi_pass 127.0.0.1:9003;
    }
    ....
}

uwsgi:
chdir = /var/www/../
module = wsgihandler
socket = 127.0.0.1:9003
wsgi-file = app/__init__.py
callable = app
master = true
chmod-socket = 664
uid = root
gid = root
processes = 4
socket-timeout = 180
post-buffering = 8192
max-requests = 1000
buffer-size = 32768
logto = /var/www/.../log/uwsgi.log
touch-reload = /var/www/.../touch_reload
6

There are 6 best solutions below

0
On BEST ANSWER

i have same issue, but the problem was in sqlalchemy, try to add this:

@app.teardown_request
def shutdown_session(exception=None):
    from extension import db
    db.session.remove()
0
On

This error means that port 9002 is already in use by another process. As per your logs that process is uwsgi probably another instance of uWSGI is running on the same address (127.0.0.1:9002). May be the port was not released while you stop flask app and your wsgi server is restarted while you run touch touch_reload. You may try the following command to release the port.

sudo fuser -k 9002/tcp

If that is a tcp process and restart your wsgi server again to see if the port is already in use.

0
On

FWIW, I had a similar issue and discovered that I was running uwsgi --http when I should have been running uwsgi --socket.

0
On

Interestingly, you will get the same Address already in use error, even if you work with sockets.

               vvvvvvvvvvv-- Socket!
error removing unix socket, unlink(): Permission denied [core/socket.c line 198]
bind(): Address already in use [core/socket.c line 230]
        ^^^^^^^^^^^^^^^-- "Address"

If you DO use sockets, see this answer.

0
On

I had the same problem, and it turned out my main module was already starting the application with app.run() on load.

So make sure app.run() is in the if __name__ == '__main__' section.

1
On

maybe you stop uwsgi by crtl + z:

  1. find the pid of process which take 8000

$ lsof -i:8000

result maybe is:

COMMAND  PID       USER   FD   TYPE ...
uwsgi   9196       xxx    4u  xxx   ...

then

$ kill 9196