11月10, 2017

How to Set Up My First Server?

如何配置个人云服务器,搭建LNMP环境

At the Beginning

For many of my classmates, it's the first time they have their own cloud server. So it's of great possibility you guys will meet many difficults, even leading to refresh the server from time to time that I have done(and probably will do in the future). I write this post to recommend a useful (definitely not the best) way to set up a cloud server.

LNMP/LAMP Environment

Mostly, people choose LNMP or LAMP as their server settings .What are LNMP and LAMP? Well, they just stand for five software which are widely used in servers to set up a basic server environment enabling web software to run on it: Linux(gtmd windows), NGINX or Apache, MySQL/Mariadb and PHP(Autoly is version 7.x but I have to point out it that because of some incompatibility problems, higher version never stands for a better performance, referring to python).

Linux

We are arranged to use Ubuntu 16.04 LTS, so let's just skip this paragraph if you are not interested with it. In fact, in my daily usage, I use CentOS and Archlinux more. Linux or Linux like system are better for developer from my perspective.

MySQL

If you have an Aliyun Cloud Server ECS, you will know that Alibaba has already removed the MySQL from the yum source, because it's rechargeable. So I suggest that you use the perfect substitute——Mariadb. This system is a branch of MySQL, open source and totally free of charge.

Apt-get Source

Servers use the Tencent source as the software source, so usually we don't have to change it. If you want to zuo a die, you can just edit the /etc/apt/sources.list by using codes bellow:

sudo vim /etc/apt/sources.list

#do something you like, like zuosi sudo apt-get update

Some codes are long. Please use computer or put your phone in horizontal direction. I only recommend the last operation.

And then, run codes bellow:

sudo apt install mariadb-server mariadb-client libmariadbd-dev libmysqlclient-dev
service mysql restart
service mysql status
Normally nothing wrong will occur. Then use the secure script to set up it:

mysql_secure_installation
Enter current password for root:[Just enter]
Set root password?[Y/n] Y

#enter your password Remove anonymous users?[Y/n] Y Disallow root login remotely?[Y/n] Y Remove test database and access to it? [Y/n] Y Reload privilege tables now?[Y/n] Y

#Thanks for using MariaDB! service mysql restart

Now you can use:

mysql -uroot -p
with root as username and the password you set to login the MariaDB-server. This server runs on port 3306. You have to write it and your server IP in your project settings if your project needs it.

NGINX or Apache?

I recommend the NGINX, for it's light-weight, high concurency support(remember the WeChat Ticket?), highly modular design. NGINX has a better property than Apache. Maybe Apache are more stabilized, but as young developers, trust me, NGINX is better.

"Why don't I use Django runserver directly?"

Because if you use NGINX or Apache, there are only few ports about web opened. All of these request for sources in different domain will be dispatched by them. But if you use the Django ./manage runserver, you have to open more ports to support it. It's not a good habit because of higher secure risk and unsteady status. And maybe Tencent secure group strategies only give you a :80.(I haven't checked it.)

Installation

sudo apt install nginx

"Why don't I install NGINX from source code?I can add module freely!"

I have tried both ways of installation. Installation from Apt or Yum source can nearly satisfy about 99% of our demand. We don't really need to redo all the steps the apt has done for you, which is wasting time and can cause many mistakes for new user.Also do the PHP and PHP-fpm. Apache support php 5 better than NGINX, but we can use phpcgi to make up it. I will teach you it bellow.

Nginx config files are in /etc/nginx/. The nginx.conf are the whole situation config of Nginx service. The directory conf.d includes all sites' unique config files. You can set up a site by adding a file in it and restart the Nginx service by:

service nginx restart
You'd better to look up for reverse proxy(反向代理) to understand what we are doing.

PHP and PHP-fpm

You have to install them to enable php file parser on your server.

sudo apt install php php-fpm
 

Install Python3 and Virtual env

Our servers have installed Python3. You can just use it by type "python3". But how could our django project use it? We can use venv to set up a python3 environment in our project, and avoid changing system's python version.

Firstly, install it.

sudo apt install python3-dev
sudo apt install python3-venv
Then you have to fork the project on gitlab.thsecourse.com and git clone it to your server. I think that I can just skip it. Then cd to your project directory and create a virtual environment.After that, activate it.

python3 -m venv .venv
source .venv/bin/activate
Using deactivate when you want to exit.

UWSGI

Uwsgi is important. We have to use it to connect the Django project to the Nginx. In our virtual environment, we can easily install it using command bellow:

pip install uwsgi
However, if you don't want to use venv, you can use pip3 after installing it (sudo apt install python3-pip) to do the same thing. And use python3 to run those python files.

 

Django

pip install Django
pip install django #yes, they are different
The python this project using is 3.x, but the python version on our server is python 2.x. We have two methods to solve this. First——install python 3.x environment on your server, and Second——transfer this project from python3 to python2. Normally add "from future import unicode_literals" to the head of all those python files using Chinese. There is a line "# -- coding: utf-8 --", but in real usage, I find it's not enough.

Connecting Django to NGINX

This is the most important step. After failing for count-loss times, I finally make it.

Manual on code.ziqiangxuetang.com about how to deploy Django on Apache and NGINX is worth reading. There is only one thing you have to pay attention to: following the steps to deploy Django on Apache is easy.But when it comes to NGINX, you have to combine them together to achieve it.

Create an uwsgi settings file called 'uwsgi.ini' and set the path correctly. I put it at the same path with the project. And modify it as codes bellow:

[uwsgi]
socket = /home/ubuntu/WeChatTicket/wct.sock
chdir = /home/ubuntu/WeChatTicket
wsgi-file = WeChatTicket/wsgi.py
touch-reload = /home/ubuntu/WeChatTicket/reload
home = /home/ubuntu/WeChatTicket/.venv/

processes = 2 threads = 4

chmod-socket = 777 chown-socket = ubuntu:ubuntu

daemonize = /home/ubuntu/wct.log

vacuum = true

You can use command

uwsgi --ini /path/to/uwsgi.ini
(in python3 environment, system or venv) to start the uwsgi.

Then create an empty file, if you want to reload the project,"touch" it

vim /home/ubuntu/WeChatTicket/reload
:wq
You can test this by use

uwsgi --ini /path/to/uwsgi.ini
If you see some error info created by our project like "FileNotFoundError: [Errno 2] No such file or directory: '/home/ubuntu/WeChatTicket/configs.json'", you got it right.

And create the unfound file:

cp configs.example.json configs.json

Check Your Steps

After steps above, you are supposed to have a file tree like this:

home
|----ubuntu
|----|----wct.log
|----|----WeChatTicket
|----|---------|-------adminpage
|----|---------|-------codex
|----|---------|-------configs.example.json
|----|---------|-------configs.json 
|----|---------|-------docs
|----|---------|-------LICENSE
|----|---------|-------manage.py
|----|---------|-------newfile
|----|---------|-------README.md
|----|---------|-------reload 
|----|---------|-------requirements.txt
|----|---------|-------static
|----|---------|-------templates
|----|---------|-------userpage
|----|---------|-------uwsgi.ini *
|----|---------|-------wct.sock
|----|---------|-------wechat
|----|---------|-------WeChatTicket

By the way, if you just want to use the python3 environment on your server, you can just change the home to the python3 path.

Next, the NGINX. We have to let nginx run as ubuntu(our user).

sudo vim /etc/nginx/nginx.conf
Change the user from www-data to ubuntu at line 1.

Then add a config file to conf.d

sudo vim /etc/nginx/conf.d/wct.conf
Fill it like this:

server {
 listen 80;
 server_name 118.89.231.177; #Exchange it to your own IP
 charset utf-8;

client_max_body_size 75M;

location /static { alias /home/ubuntu/WeChatTicket/static; }

location / { uwsgi_pass unix:///home/ubuntu/WeChatTicket/wct.sock; include /etc/nginx/uwsgi_params; } }

Restart Nginx:

(sudo) service nginx restart
Now you can insert you IP address to your broser address blank. And get a "Internal Server Error" for we haven't set our project correctly. If you got a 502, please concat me or check out the log file at /var/log/nginx/error.log and try to fix it.

Let's check the ~/wct.log. We get following information:

FileNotFoundError: [Errno 2] No such file or directory: '/home/ubuntu/WeChatTicket/configs.json'
So make it.

cp configs.example.json configs.json
And restart nginx as I said. Now the whole system is supposed to work. But I find that the django version we have installed is higher than the project, so run this:

cd /home/ubuntu/WeChatTicket
source .venv/bin/activate
pip install -r requirements.txt
If you do all of those above and still can't make it, please just concat me and let me know it. I will try my best.

(For students at thss, if you see the notice "not found page 404 create by django", you have made it. )

Setup WeChat developer server

Just follow the homework file <developer instruction>.

WeChat Url is http://yourip/wechat

WeChat Token is a string you create at random

You have to set up a database for your Django project, and set it correctly in your WeChatTicket.settings.

 

Some Errors Found in Usage

ERROR 1698 (28000): Access denied for user 'root'@'localhost'

$ sudo mysql -u root # I had to use "sudo" since is new installation

mysql> USE mysql; mysql> UPDATE user SET plugin='mysql_native_password' WHERE User='root'; mysql> FLUSH PRIVILEGES; mysql> exit;

$ service mysql restart

Q & A

Q:How do I enable it after I made some changes in project?

A:You have to restart both uwsgi and nginx. Remember the empty file "reload" we have created? CD to the directory and do next:

touch reload
(sudo) service nginx restart
 

Q:Do I need to run Django like this: "python manage.py runserver 0:80"?

A: Not at all. Now you have the nginx and uwsgi do the same thing. When you start uwsgi and Nginx, all of your request will be accepted by nginx first, then be sent to uwsgi. Uwsgi transfer your request to Django.

Any question you want to ask me can be commented under this post. If you have some problems, please let me know it. And I will share how to solve it.

 

Q:Download django in virtualenvironment is too f**king slow?

A:Because you are using foreign pip source, try this:

pip install ** -i https://pypi.tuna.tsinghua.edu.cn/simple

Then pip will use Tuna Source to download packages.

 

Q:Installing requirements.txt failed with "mysql_config not found"?

A:You forgot to install package libmysqlclient-dev:

sudo apt install libmysqlclient-dev

 

Q:Cannot restart nginx?

A:Check your nginx config file in /etc/nginx/conf.d/wct.conf. Maybe you have lost an 'S' at the beginning of the file. If so, you have to learn how to use Vim.

 

Q:Default problem solution?

A:Check your server log "wct.log" and "/var/log/nginx/error.log".

本文链接:https://blog.magichc7.com/post/how-to-set-up-my-first-server?.html

-- EOF --

相关评论