1、打开DigitalOcean并注册虚拟机

一直都有的优惠码

最近活动,注册就送100刀,限时使用2个月

2、新建一个Droplet


3、选择操作系统,配置ssh,然后新建create



这个选项是在你本地的计算机上生成公钥,复制到New SSH Key里面,然后就可以免密码ssh到vps了

生成公钥步骤:

[email protected] ~ $ ssh-keygen

Generating public/private rsa key pair.

Enter file
in
which to save the key (/home/hadoop/.ssh/id_rsa): /home/hadoop/.ssh/id_rsa_digitocean

Enter passphrase (empty for no passphrase):

Enter same passphrase again:

Your identification has been saved in /home/hadoop/.ssh/id_rsa_digitocean.

Your public key has been saved in /home/hadoop/.ssh/id_rsa_digitocean.pub.

The key’s randomart image is:

+—[RSA 2048]—-+

| . o|

| . ++|

| +. =o++.|

| S o*.Bo..|

| . o=++O. |

| ++++=+|

| . +.+=.|

| + . o+|

+—-[SHA256]—–+

[email protected] ~ $ ls ./.ssh/

authorized_keys id_rsa_digitocean id_rsa.pub

id_rsa id_rsa_digitocean.pub known_hosts

[email protected] ~ $ cat ./.ssh/id_rsa_digitocean.pub

这里的公钥复制下来,粘贴到digitalOcean “New SSH KEY”

[email protected] ~ $ ssh-add ~/.ssh/id_rsa_digitocean

Identity added: /home/hadoop/.ssh/id_rsa_digitocean (/home/hadoop/.ssh/id_rsa_digitocean)

[email protected] ~ $ ssh-add -l

2048 SHA256:Vpo33okny7YLpZLxcVPUe8Eo /home/hadoop/.ssh/id_rsa_digitocean (RSA)

2048 SHA256:Vpo33okny7PBsZLxcVPUe8Eo [email protected] (RSA)

2048 SHA256:Swzv6FoCm78RBbNSkLvlcsYA [email protected] (RSA)

[email protected] ~ $
ssh [email protected]

Welcome to Ubuntu 18.04.1 LTS (GNU/Linux 4.15.042-generic x86_64)

* Documentation: https://help.ubuntu.com

* Management: https://landscape.canonical.com

* Support: https://ubuntu.com/advantage

4、点击create后等待生成


5、获取到IP尝试ssh登陆


6、在vps上新建djangoadmin用户,并赋予root权限

adduser djangoadmin

usermod -aG sudo djangoadmin

为了能在本地计算机上ssh这个新用户,需要在/home/djangoadmin下新建 mkdir .ssh

cd /home/djangoadmin

mkdir ./.ssh

vi authorized_keys

将本地计算机的public key复制到vps上的authorized_keys里面

[email protected]:/home/djangoadmin/.ssh# nano authorized_keys

[email protected]:/home/djangoadmin/.ssh# nano authorized_keys

[email protected]:/home/djangoadmin/.ssh# cat authorized_keys

ssh-rsa AAAAB3NzaC1yc2EAAAd+5eCPzWBXNNoUwSybiBepIbE7a0BeI6Q1rvbTYeuIWuWHfY6wbToQ37Pc1QwfMsBy4qc2b9JUdpCFevZwS5MCFAe+bUDOfxFwJOchzOmk9rQ+ep6wuUzYpFjewh0CTlG85ApW6y2oYnokTb+O2ZZrjqdh/3qJLmVDgp+yxKeuyOfhy8oOYV2YFZheGJ3Nf5y5Rc9vEmgXCOMNpjp5wN [email protected]

[email protected]:/home/djangoadmin/.ssh# exit

logout

Connection to 104.248.244.237 closed.

[email protected] ~ $ sudo
ssh [email protected]104.248.244.237

7、关闭root登陆权限

sudo vi /etc/ssh/sshd_config

#HostKey /etc/ssh/ssh_host_rsa_key

#HostKey /etc/ssh/ssh_host_ecdsa_key

#HostKey /etc/ssh/ssh_host_ed25519_key

# Ciphers and keying

#RekeyLimit default none

# Logging

#SyslogFacility AUTH

#LogLevel INFO

# Authentication:

#LoginGraceTime 2m

PermitRootLogin yes
#change to No

#StrictModes yes

#MaxAuthTries 6

#MaxSessions 10

#PubkeyAuthentication yes

重启启动ssh服务

sudo systemctl reload sshd

8、打开防火墙

sudo ufw app list

sudo ufw allow OpenSSH

sudo ufw enable

[email protected]:~$ sudo ufw app list

[sudo] password for djangoadmin:

Available applications:

OpenSSH

[email protected]:~$ sudo ufw allow OpenSSH

Rules updated

Rules updated (v6)

[email protected]:~$ sudo ufw enable

Command may disrupt existing ssh connections. Proceed with operation (y|n)? y

Firewall is active and enabled on system startup

[email protected]:~$

[email protected]:~$

[email protected]:~$ sudo ufw status

Status: active

To Action From

— —— —-

OpenSSH ALLOW Anywhere

OpenSSH (v6)              ALLOW      Anywhere (v6)  

9、更新软件

sudo apt update

sudo apt upgrade

安装python3、apache、nginx、curl

sudo apt-get install python3-pip apache2 libapache2-mod-wsgi-py3  nginx curl

安装mysql

或者

安装postgresql

10、配置虚拟环境

# sudo apt install python3-venv

新建app安装目录

[email protected]:~$ mkdir pyapps

[email protected]:~$ cd pyapps/

[email protected]:~/pyapps$ python3 -m venv ./venv

[email protected]:~/pyapps$

[email protected]:~/pyapps$ source ./venv/bin/activate

(venv) [email protected]:~/pyapps$

11、用Git传代码

在本地计算机生成requirement.txt

(myprojectenv) [email protected] ~/myproject/myproject $ pip freeze > requirment.txt

(myprojectenv) [email protected] ~/myproject/myproject $ cat requirment.txt

Django==2.1.2

mysqlclient==1.3.13

pytz==2018.6

(myprojectenv) [email protected] ~/myproject/myproject $

git提交代码

(myprojectenv) [email protected] ~/myproject/myproject $
cat requirment.txt

Django==2.1.2

mysqlclient==1.3.13

pytz==2018.6

(myprojectenv) [email protected] ~/myproject/myproject $
git add .

(myprojectenv) [email protected] ~/myproject/myproject $ git commit -m ‘Added requirement.txt file’

[master 8d9b2b6] Added requirement.txt file

file changed, 3 insertions(+)

create mode 100644 requirment.txt

(myprojectenv) [email protected] ~/myproject/myproject $ git push

warning: push.default is unset; its implicit value has changed in

Git 2.0 from ‘matching’ to ‘simple’. To squelch this message

and maintain the traditional behavior, use:

git config –global push.default matching

To squelch this message and adopt the new behavior now, use:

git config –global push.default simple

Counting objects: 3, done.

Delta compression using up to 2 threads.

Compressing objects: 100% (2/2), done.

Writing objects: 100% (3/3), 332 bytes | 0 bytes/s, done.

Total 3 (delta 1), reused 0 (delta 0)

remote: Resolving deltas: 100% (1/1), completed with 1
local object.

To https://github.com/crsbrk/HRSystemByDjango.git

b58139b..8d9b2b6 master -> master

(myprojectenv) [email protected] ~/myproject/myproject $

在远程vps机器上clone

(venv) [email protected]:~/pyapps$ git clone https://github.com/crsbrk/HRSystemByDjango.git

Cloning into ‘HRSystemByDjango’

remote: Enumerating objects: 650, done.

remote: Counting objects: 100% (650/650), done.

remote: Compressing objects: 100% (454/454), done.

remote: Total 650 (delta 207), reused 620 (delta 177), pack-reused 0

Receiving objects: 100% (650/650), 8.90 MiB | 11.87 MiB/s, done.

Resolving deltas: 100% (207/207), done.

安装pip需要的文件

(venv) [email protected]:~/pyapps$ cd HRSystemByDjango/

(venv) [email protected]:~/pyapps/HRSystemByDjango$ pip install -r requirment.txt

Collecting Django==2.1.2 (from -r requirment.txt (line 1))

Downloading https://files.pythonhosted.org/packages/32/ab/22530cc1b2114e6067eece94a333d6c749fa1c56a009f0721e51c181ea53/Django-2.1.2-py3-none-any.whl (7.3MB)


100% |████████████████████████████████| 7.3MB 172kB/s

Collecting mysqlclient==1.3.13 (from -r requirment.txt (line 2))

Downloading https://files.pythonhosted.org/packages/ec/fd/83329b9d3e14f7344d1cb31f128e6dbba70c5975c9e57896815dbb1988ad/mysqlclient-1.3.13.tar.gz (90kB)


100% |████████████████████████████████| 92kB 9.7MB/s

Collecting pytz==2018.6 (from -r requirment.txt (line 3))

Downloading https://files.pythonhosted.org/packages/52/8b/876c5745f617630be90cfb8fafe363c6d7204b176dc707d1805d1e9a0a35/pytz-2018.6-py2.py3-none-any.whl (507kB)


100% |████████████████████████████████| 512kB 2.4MB/s

Building wheels for collected packages: mysqlclient

Running setup.py bdist_wheel for mysqlclient … error

Complete output from command /home/djangoadmin/pyapps/venv/bin/python3 -u -c “import setuptools, tokenize;__file__=’/tmp/pip-build-nxv5a8ev/mysqlclient/setup.py’;f=getattr(tokenize, ‘open’, open)(__file__);code=f.read().replace(‘\r\n’, ‘\n’);f.close();exec(compile(code, __file__, ‘exec’))” bdist_wheel -d /tmp/tmp35y27flfpip-wheel- –python-tag cp36:

/usr/lib/python3.6/distutils/dist.py:261: UserWarning: Unknown distribution option: ‘long_description_content_type’

warnings.warn(msg)

usage: -c [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] …]

or: -c –help [cmd1 cmd2 …]

or: -c –help-commands

or: -c cmd –help

error: invalid command
‘bdist_wheel’

—————————————-

Failed building wheel for mysqlclient

Running setup.py clean for mysqlclient

Failed to build mysqlclient

Installing collected packages: pytz, Django, mysqlclient

Running setup.py install
for mysqlclient … done

Successfully installed Django-2.1.2 mysqlclient-1.3.13 pytz-2018.6

(venv) [email protected]:~/pyapps/HRSystemByDjango$

12、生产服务器配置 localsetting

localsetting

在setting.py 配置完成后,通过

git add .

git commit -m 'add localsetting'

git push

提交代码完成后,在vps上pull下来代码

(venv) [email protected]:~/pyapps/HRSystemByDjango$ git pull

remote: Enumerating objects: 11, done.

remote: Counting objects: 100% (11/11), done.

remote: Compressing objects: 100% (2/2), done.

remote: Total 6 (delta 4), reused 6 (delta 4), pack-reused 0

Unpacking objects: 100% (6/6), done.

From https://github.com/crsbrk/HRSystemByDjango

8d9b2b6..cb1c838 master -> origin/master

Updating 8d9b2b6..cb1c838

Fast-forward

myproject/__pycache__/settings.cpython-35.pyc | Bin 2825 -> 2906 bytes

myproject/settings.py | 9 +++++++++

2 files changed, 9 insertions(+)

(venv) [email protected]:~/pyapps/HRSystemByDjango$ ls

bonuses db.sqlite3 myproject posts scores templates

cutovers manage.py orders requirment.txt static

(venv) [email protected]:~/pyapps/HRSystemByDjango$ cat myproject/settings.py

在远程的VPS计算机上新建local_setting.py

配置隐私的一些信息,

  • SECRET_KEY
  • ALLOWED_HOSTS
  • DATABASES
  • DEBUG
  • EMAIL_*

# SECURITY WARNING: keep the secret key used in production secret!

SECRET_KEY = ‘*#2m()bwk*vod$kf&csdf2%a79bq2%&26515^i2#$8-lq57=5z1=-9’

# SECURITY WARNING: don’t run with debug turned on in production!

DEBUG = False

ALLOWED_HOSTS = [“104.248.244.237”]

DATABASES = {
‘default’: {
‘ENGINE’: ‘django.db.backends.mysql’,
‘NAME’: ‘workstaff’,
‘USER’:’root’,
‘PASSWORD’:’root’,
‘HOST’:’localhost’,
‘PORT’:”
}
}

在本地的setting.py可以删掉这些隐私信息,也可以不删,local_setting.py会覆盖setting.py中相同的配置,添加没有的配置,然后提交代码到git

在远程的vps主机,用git pull同步代码

13、数据库migrate

python manage.py makemigrations

提示:

django.db.utils.OperationalError: (1698, “Access denied for user 'root'@'localhost'”)

按照如下修改:

create user ‘django’@‘localhost’ identified by
‘django-user-password’;

grant usage on *.* to ‘django’@‘localhost’;

grant all privileges on django-database-1.* to ‘django’@‘localhost’;

不仅换了数据库用户名和密码,

最后发现没有用,还是提示被拒绝了。

修改setting.py,把数据库部分配置删掉,就可以正常运行了。

(venv) [email protected]:~/pyapps/HRSystemByDjango/myproject$ vi settings.py

(venv) [email protected]:~/pyapps/HRSystemByDjango/myproject$ python manage.py makemigrations

python: can‘t open file ‘manage.py’: [Errno 2] No such file or directory

(venv) [email protected]:~/pyapps/HRSystemByDjango/myproject$ cd ..

(venv) [email protected]:~/pyapps/HRSystemByDjango$ python manage.py makemigrations

Migrations for
‘bonuses’:

bonuses/migrations/0003_auto_20181209_2321.py

– Alter field is_delayed on bonuses

– Alter field pj_leader on bonuses

– Alter field pj_participant1 on bonuses

– Alter field pj_participant2 on bonuses

– Alter field pj_participant3 on bonuses

– Alter field workload_allot on bonuses

– Alter field workload_allot1 on bonuses

– Alter field workload_allot2 on bonuses

– Alter field workload_allot3 on bonuses

Migrations for
‘cutovers’:

cutovers/migrations/0003_auto_20181209_2321.py

– Alter field is_delayed on cutovers

– Alter field pj_leader on cutovers

Migrations for
‘orders’:

migrate的时候提示database配置错误

原因:local_setting.py没有放到setting.py目录里面

再一次migrate

django.db.utils.OperationalError: (1067, “Invalid default value for 'orders_type'”)

因为model.py中 orders_type的默认值是中文,建立数据库的时候忘记修改表的编码格式为utf-8了,所以提示这个错误。

删除数据库,新建数据库修改编码格式,删除每个APP下的migrations文件夹

(venv) [email protected]:~/pyapps/HRSystemByDjango$ python manage.py migrate

Operations to perform:

Apply all migrations: admin, auth, contenttypes, sessions

Running migrations:

Applying contenttypes.0001_initial… OK

Applying auth.0001_initial… OK

Applying admin.0001_initial… OK

Applying admin.0002_logentry_remove_auto_add… OK

Applying admin.0003_logentry_add_action_flag_choices… OK

Applying contenttypes.0002_remove_content_type_name… OK

Applying auth.0002_alter_permission_name_max_length… OK

Applying auth.0003_alter_user_email_max_length… OK

Applying auth.0004_alter_user_username_opts… OK

Applying auth.0005_alter_user_last_login_null… OK

Applying auth.0006_require_contenttypes_0002… OK

Applying auth.0007_alter_validators_add_error_messages… OK

Applying auth.0008_alter_user_username_max_length… OK

Applying auth.0009_alter_user_last_name_max_length… OK

Applying sessions.0001_initial… OK

(venv) [email protected]:~/pyapps/HRSystemByDjango$

 新建超级用户:

(venv) [email protected]:~/pyapps/HRSystemByDjango$ python manage.py createsuperuser

collectstatic:

(venv) [email protected]:~/pyapps/HRSystemByDjango$ python manage.py collectstatic

You have requested to collect static files at the destination

location as specified in your settings:

/home/djangoadmin/pyapps/HRSystemByDjango/static

This will overwrite existing files!

Are you sure you want to do this?

Type ‘yes’ to continue, or ‘no’ to cancel: yes

119 static files copied to ‘/home/djangoadmin/pyapps/HRSystemByDjango/static’, 221 unmodified.

防火墙放开端口8000:

(venv) [email protected]:~/pyapps/HRSystemByDjango$ sudo ufw allow 8000

访问vps 公网ip地址 104.248.244.237,没有图片,没有css

如果DEBUG设置为false,如果利用

 python manage.py runserver 0.0.0.0:8000

服务器不会加载static文件夹

DEBUG 为True是开发模式, python manage.py runserver 0.0.0.0:8000也是开发模式

14、安装Gunicorn

Gunicorn”Green Unicorn”是一个Python Web服务器网关接口HTTP服务器。

https://gunicorn.org/

安装:

(venv) [email protected]:~/pyapps/HRSystemByDjango/myproject$ pip install gunicorn

Collecting gunicorn

Downloading https://files.pythonhosted.org/packages/8c/da/b8dd8deb741bff556db53902d4706774c8e1e67265f69528c14c003644e6/gunicorn-19.9.0-py2.py3-none-any.whl (112kB)


100% |████████████████████████████████| 122kB 8.7MB/s

Installing collected packages: gunicorn

Successfully installed gunicorn-19.9.0

(venv) [email protected]:~/pyapps/HRSystemByDjango/myproject$

绑定端口

gunicorn –bind 0.0.0.0:8000 yourproject.wsgi

(venv) [email protected]:~/pyapps/HRSystemByDjango$ gunicorn –bind 0.0.0.0:8000 myproject.wsgi

[20181210
06:49:48 +0000] [14889] [INFO] Starting gunicorn 19.9.0

[20181210
06:49:48 +0000] [14889] [INFO] Listening at: http://0.0.0.0:8000 (14889)

[20181210
06:49:48 +0000] [14889] [INFO] Using worker: sync

[20181210
06:49:48 +0000] [14892] [INFO] Booting worker with pid: 14892

用浏览器访问公网vps ip,出现如下提示

Not Found: /static/css/bootstrap.css

Not Found: /static/css/all.css

Not Found: /static/css/style.css

Not Found: /static/css/lightbox.min.css

Not Found: /static/welcom/css/main.css

Not Found: /static/js/lightbox.min.js

Not Found: /static/js/main.js

Not Found: /static/img/yunwei.png

Not Found: /static/css/bootstrap.css

Not Found: /static/css/style.css

Not Found: /static/css/lightbox.min.css

Not Found: /static/welcom/css/main.css

Not Found: /static/js/main.js

ctrl+c 退出gunicorn,退出虚拟环境

^C[20181210
06:53:25 +0000] [14889] [INFO] Handling signal: int

[20181210
14:53:25 +0800] [14892] [INFO] Worker exiting (pid: 14892)

[20181210
06:53:25 +0000] [14889] [INFO] Shutting down: Master

(venv) [email protected]:~/pyapps/HRSystemByDjango$ deactivate

打开文件 gunicorn.socket

# sudo nano /etc/systemd/system/gunicorn.socket

将下面的代码复制进去,并保存

[Unit]
Description=gunicorn socket

[Socket]
ListenStream=/run/gunicorn.sock

[Install]
WantedBy=sockets.target

打开文件 gunicorn.service

# sudo nano /etc/systemd/system/gunicorn.service

复制并保存

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

[Service]
User=djangoadmin
Group=www-data
WorkingDirectory=/home/djangoadmin/pyapps/HRSystemByDjango
ExecStart=/home/djangoadmin/pyapps/venv/bin/gunicorn \
–access-logfile – \
–workers 3 \
–bind unix:/run/gunicorn.sock \
myproject.wsgi:application

[Install]
WantedBy=multi-user.target

启动服务,并且设置启动自动开启服务

# sudo systemctl start gunicorn.socket #启动

# sudo systemctl enable gunicorn.socket #开机自启动

查看 guinicorn状态

# sudo systemctl status gunicorn.socket

查看是否存在 gunicorn.sock

# file /run/gunicorn.sock

查看错误日志

 sudo journalctl -u gunicorn

[email protected]:~/pyapps/HRSystemByDjango$ sudo journalctl -u gunicorn

— Logs begin at Sun 20181209
09:18:18 UTC, end at Mon 20181210
07:59:43 UTC. —

Dec 10
07:20:11 ubuntu1 systemd[1]: /etc/systemd/system/gunicorn.service:20: Missing ‘=’.

Dec 10
07:54:30 ubuntu1 systemd[1]: /etc/systemd/system/gunicorn.service:20: Missing ‘=’.

[email protected]:~/pyapps/HRSystemByDjango$

发现 gunicorn.service 配置错误,但是怎么restart都不管用,还是提示参数错误,Missing ‘=’

如果修改了gunicorn.service要运行下面这两行代码才能重新加载

systemctl daemon-reload

systemctl restart gunicorn.service

参考:https://serverfault.com/questions/892944/gunicorn-not-creating-socket-on-nginx

[email protected]:~/pyapps/venv/bin$ systemctl daemon-reload

==== AUTHENTICATING FOR org.freedesktop.systemd1.reload-daemon ===

Authentication is required to reload the systemd state.

Authenticating as: ,,, (djangoadmin)

Password:

==== AUTHENTICATION COMPLETE ===

[email protected]:~/pyapps/venv/bin$ systemctl restart gunicorn.service

==== AUTHENTICATING FOR org.freedesktop.systemd1.manage-units ===

Authentication is required to restart ‘gunicorn.service’.

Authenticating as: ,,, (djangoadmin)

Password:

==== AUTHENTICATION COMPLETE ===

djangoadmin[email protected]:~/pyapps/venv/bin$ sudo systemctl status gunicorn.socket

Failed to dump process list, ignoring: No such file or directory

● gunicorn.socket – gunicorn socket

Loaded: loaded (/etc/systemd/system/gunicorn.socket; enabled; vendor preset: enabled)

Active: active (running) since Mon 20181210
10:21:00 UTC; 37s ago

Listen: /run/gunicorn.sock (Stream)

CGroup: /system.slice/gunicorn.socket

Dec 10
10:21:00 ubuntu1 systemd[1]: Listening on gunicorn socket.

[email protected]:~/pyapps/venv/bin$

测试是否成功启动

curl –unix-socket /run/gunicorn.sock localhost

 输入这条命令后会返回html

15、配置Nginx 到Gunicorn

将Debug改为false      

[email protected]:~/pyapps/HRSystemByDjango/myproject$ vi local_settings.py      

sudo nano /etc/nginx/sites-available/HRSystemByDjango

复制下面代码,配置vps ip地址,及目录

server {
listen 80;
server_name 104.248.244.237;

location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /home/djangoadmin/pyapps/HRSystemByDjango;
}

location /media/ {
root /home/djangoadmin/pyapps/HRSystemByDjango;
}

location / {
include proxy_params;
proxy_pass http://unix:/run/gunicorn.sock;
}
}

 

 链接到目录 sites-enabled

sudo ln -s /etc/nginx/sites-available/HRSystemByDjango /etc/nginx/sites-enabled

测试:

sudo nginx -t

[email protected]:~/pyapps/HRSystemByDjango$ sudo nginx -t

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok

nginx: configuration file /etc/nginx/nginx.conf test is successful

重新启动Nginx

sudo systemctl restart nginx

出现错误:

[email protected]:~/pyapps/HRSystemByDjango$ sudo systemctl restart nginx

Job for nginx.service failed because the control process exited with error code.

See “systemctl status nginx.service” and “journalctl -xe”
for details.

查看日志

[email protected]:~/pyapps/HRSystemByDjango/myproject$ systemctl status nginx.service

● nginx.service – A high performance web server and a reverse proxy server

Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)

Active: failed (Result: exit-code) since Mon 20181210
11:08:41 UTC; 7s ago

Docs: man:nginx(8)

Process: 16068 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=1/FAILURE)

Process: 16058 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS)

[email protected]:~/pyapps/HRSystemByDjango/myproject$ /var/log/nginx/error.log.

查看log

[email protected]:~/pyapps/HRSystemByDjango/myproject$
sudo
cat /var/log/nginx/error.log

2018/12/10
10:46:57 [emerg] 15869#15869: bind() to 0.0.0.0:80 failed (98: Address already in use)

2018/12/10
10:46:57 [emerg] 15869#15869: bind() to [::]:80 failed (98: Address already in use)

2018/12/10
10:46:57 [emerg] 15869#15869: bind() to 0.0.0.0:80 failed (98: Address already in use)

2018/12/10
10:46:57 [emerg] 15869#15869: bind() to [::]:80 failed (98: Address already in use)

2018/12/10
10:46:57 [emerg] 15869#15869: bind() to 0.0.0.0:80 failed (98: Address already in use)

2018/12/10
10:46:57 [emerg] 15869#15869: bind() to [::]:80 failed (98: Address already in use)

2018/12/10
10:46:57 [emerg] 15869#15869: bind() to 0.0.0.0:80 failed (98: Address already in use)

2018/12/10
10:46:57 [emerg] 15869#15869: bind() to [::]:80 failed (98: Address already in use)

2018/12/10
10:46:57 [emerg] 15869#15869: bind() to 0.0.0.0:80 failed (98: Address already in use)

2018/12/10
10:46:57 [emerg] 15869#15869: bind() to [::]:80 failed (98: Address already in use)

2018/12/10
10:46:57 [emerg] 15869#15869: still could not bind()

 

查询端口占用情况

[email protected]:~/pyapps/HRSystemByDjango/myproject$
netstat -ntpl

(Not all processes could be identified, non-owned process info

will not be shown, you would have to be root to see it all.)

Active Internet connections (only servers)

Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name

tcp 0 0 127.0.0.53:53 0.0.0.0:* LISTEN –
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN –
tcp 0 0 127.0.0.1:3306 0.0.0.0:* LISTEN –
tcp6 0 0 :::80 :::* LISTEN –
tcp6 0 0 :::22 :::* LISTEN –

 

看到ipv6 80端口被占用了,看下是哪个程序的

[email protected]:~/pyapps/HRSystemByDjango/myproject$ sudo
netstat -ntpl

Active Internet connections (only servers)

Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name

tcp6 0 0 :::80 :::* LISTEN 8802/apache2

这里是apache2的进行占用,所以kill了它

sudo kill 8802 

再启动Nginx就可以成功了

sudo systemctl start nginx

移除防火墙端口 8000,允许所有的Nginx

# sudo ufw delete allow 8000

# sudo ufw allow ‘Nginx Full’

配置服务器图片大小

打开 nginx 配置文件

sudo nano /etc/nginx/nginx.conf

添加下面这条命令到 http{}

client_max_body_size 20M; #上传文件大小最大20MB 

重启 NGINX

sudo systemctl restart nginx

media文件问题

图片如果不显示. 建议删除media文件夹下的photos

# sudo rm -rf media/photos

浏览器访问vps ip地址,发现无法访问


原因是防火墙配置问题,添加如下命令就行了。

sudo ufw allow ‘Nginx Full’

 

16、域名配置

到域名商那里添加如下配置

@ A Record YOUR_IP_ADDRESS

www CNAME example.com


 

在服务器的 local_settings.py 文件中修改 “ALLOWED_HOSTS”,添加域名

ALLOWED_HOSTS = [‘IP_ADDRESS’, ‘example.com’, ‘www.example.com’]

编辑 /etc/nginx/sites-available/HRSystemByDjango

server {

listen: 80;

server_name xxx.xxx.xxx.xxx example.com www.example.com;

}

server {

listen 80;

server_name 104.248.244.237 tsla.space www.tsla.space;

}

重新启动 NGINX 和 Gunicorn

# sudo systemctl restart nginx

# sudo systemctl restart gunicorn

17、终于可以通过域名访问站点了


附录:

digitOcean搭建:

https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04

django部署教学:

https://gist.github.com/bradtraversy/cfa565b879ff1458dba08f423cb01d71#enable-the-file-by-linking-to-the-sites-enabled-dir

80端口占用:

https://blog.csdn.net/yusiguyuan/article/details/20565337

配置gunicorn

https://docs.gunicorn.org/en/stable/deploy.html?highlight=gunicorn.socket




发表评论

电子邮件地址不会被公开。 必填项已用*标注