华南农业大学Linux课程综合实验——用Java、PHP、Go、Nodejs语言,实现从MySQL读取内容并显示在浏览器上

文章目录

开始前的准备工作

1、安装Xshell和Xftp

在这里插入图片描述

2、购买/试用/学生免费领取 阿里云服务器

服务器购买:云服务器ECS_云主机_服务器托管_弹性计算-阿里云
云产品试用:阿里云试用中心_云服务器试用_企业试用场景_开发者云产品试用
学生的学习与优惠:开发者成长计划

3、服务器初始配置

点击右上角的控制台->点击云服务器 ECS->点击实例ID
在这里插入图片描述
1、创建快照
点击快照->点击创建快照

2、修改实例名称
可改可不改。实例名称改为wu2,那么远程连接时有[root@wu2 ~]#

3、重置服务器密码,然后用Xshell远程连接服务器
点击重置实例密码来设置服务器密码->在Xshell中通过账号(root)密码(你刚刚重置的实例密码)进行远程登录服务器。

因为阿里云上重置实例密码,它对密码的格式有要求,你重置的密码你可能记不住,那么可以在用重置的密码通过Xshell远程登录服务器后,通过passwd命令重置密码,此时对密码没有格式要求,可以写你能记住的密码,之后通过账号(root)密码(你刚刚用passwd重置的密码)进行远程登录服务器。

[root@wu2 ~]# passwd
Changing password for user root.
New password: 
Retype new password: 
passwd: all authentication tokens updated successfully.

Xshell中可以通过 文件->属性->外观 来设置XShell中显示的字号,我设置为14。

开始部署服务器

1、MySQL的安装和配置 + Nginx的安装

(1) MySQL的安装(rpm安装)和配置

1、rpm安装MySQL并修改MySQL密码

下载MySQL的rpm包:MySQL :: Download MySQL Yum Repository

在这里插入图片描述

点击No thanks, just start my download.,将mysql80-community-release-el7-3.noarch.rpm下载到本地电脑上。

下载后,用Xftp将其上传到服务器的/opt/school_linux_final_test/java下。

[root@wu2 ~]# yum install -y /opt/school_linux_final_test/java/mysql80-community-release-el7-3.noarch.rpm 
[root@wu2 ~]# yum list mysql*
[root@wu2 ~]# yum install -y mysql-community-server.x86_64
[root@wu2 ~]# systemctl start mysqld
[root@wu2 ~]# systemctl status mysqld	# 确保mysql已经启动
[root@wu2 ~]# mysql -V	# 查看mysql版本
mysql  Ver 8.0.25 for Linux on x86_64 (MySQL Community Server - GPL)
[root@wu2 ~]# grep 'password' /var/log/mysqld.log	# 查看mysql初始密码
2021-05-31T07:49:15.049572Z 6 [Note] [MY-010454] [Server] A temporary password is generated for root@localhost: h9fif6176K>!
[root@wu2 ~]# mysql -u root -p
Enter password: 							# 密码是前面grep命令查出的密码:h9fif6176K>!
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 8.0.25
。。。

mysql> alter user root@localhost identified by 'a1b2c3';	# 修改密码。密码太简单,会报错,如下。
ERROR 1819 (HY000): Your password does not satisfy the current policy requirements

mysql> alter user root@localhost identified by 'Nowcoder_123';		# 修改密码,这里密码必须有大写字母,有数字,有特殊符号。
Query OK, 0 rows affected (0.01 sec)

mysql> exit
Bye
[root@wu2 ~]# mysql -u root -pNowcoder_123
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 9
Server version: 8.0.25 MySQL Community Server - GPL
。。。
2、在服务器的MySQL里执行如下sql语句:
CREATE DATABASE `linux_test`CHARACTER SET utf8 COLLATE utf8_general_ci; 
USE `linux_test`; 
CREATE TABLE `linux_test`.`student`( `id` INT(11) NOT NULL AUTO_INCREMENT, `student_id` VARCHAR(50), `student_name` VARCHAR(50), PRIMARY KEY (`id`) ) ENGINE=INNODB CHARSET=utf8 COLLATE=utf8_general_ci;
INSERT INTO `linux_test`.`student` (`id`, `student_id`, `student_name`) VALUES (NULL, '2018xxxxxxxx', 'xxx'); 
INSERT INTO `linux_test`.`student` (`student_id`, `student_name`) VALUES ('1111', '其他学生'); 

(2) Nginx的安装(yum安装)

1、yum安装Nginx
[root@wu2 ~]# yum list nginx*
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
Available Packages
nginx.x86_64                                                            1:1.16.1-3.el7                                      epel
。。。
[root@wu2 ~]# yum install -y nginx.x86_64
[root@wu2 ~]# vim /etc/nginx/nginx.conf	# `/etc/nginx/nginx.conf`是nginx的配置文件
2、配置Nginx
[root@wu2 ~]# vim /etc/nginx/nginx.conf	

    location /index.java {
            proxy_pass   http://127.0.0.1:8080/;
}

	location ~ \.php$ {
        	root   /usr/share/nginx/html;
	        fastcgi_pass   127.0.0.1:9000;  #php-fpm默认的端口是9000
	        fastcgi_index  index.php;
        	fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
	        include        fastcgi_params;
	 }

	location ~ \.go$ {
		proxy_pass   http://127.0.0.1:8000;
	} 
	location ~ \.js$ {
		proxy_pass   http://127.0.0.1:8001;
	}

[root@wu2 ~]# service nginx restart

这里先列一下nginx的配置,在用四种语言:Java、PHP、Go、Nodejs,实现对应语言的程序后,可以通过下方网址来访问对应的程序。

语言标准网址其他网址
Javahttp://120.79.212.4/index.javahttp://120.79.212.4:8080/
PHPhttp://120.79.212.4/index.php
Gohttp://120.79.212.4/index.gohttp://120.79.212.4:8000/ 。 http://120.79.212.4/xxx.go
Nodejshttp://120.79.212.4/index.jshttp://120.79.212.4:8001/ 。 http://120.79.212.4/xxx.js

2、开启 阿里云安全组 和 服务器防火墙 的端口

要开启的端口有:

端口描述
80HTTP、Nginx。
8000我的测试端口,测试Go。
8001我的测试端口,测试Nodejs。
8080Tocmat。测试Java。
9000没有用到。php-fpm,PHP。

开启阿里云安全组的端口,可视化界面开启,举例如下:
在这里插入图片描述
开启服务器防火墙的端口:

[root@wu2 ~]# systemctl status firewalld	# 查看防火墙状态
[root@wu2 ~]# service firewalld start		# 开启防火墙
[root@wu2 ~]# firewall-cmd --zone=public --add-port=80/tcp --permanent
[root@wu2 ~]# firewall-cmd --zone=public --add-port=8000/tcp --permanent
[root@wu2 ~]# firewall-cmd --zone=public --add-port=8001/tcp --permanent
[root@wu2 ~]# firewall-cmd --zone=public --add-port=8080/tcp --permanent
[root@wu2 ~]# firewall-cmd --zone=public --add-port=9000/tcp --permanent
[root@wu2 ~]# service firewalld restart		# 开放端口、移除端口后,都要重启防火墙才生效
[root@wu2 ~]# firewall-cmd --list-ports		# 查看开放了哪些端口

小知识:Linux防火墙基本命令。

# 查看防火墙状态
systemctl status firewalld

# 开启、重启、关闭 防火墙
# 开启
service firewalld start
# 重启
service firewalld restart
# 关闭
service firewalld stop

# 查看防火墙规则
firewall-cmd --list-all		# 查看全部信息
firewall-cmd --list-ports	# 只看端口信息

# 查询端口是否开放
firewall-cmd --query-port=8080/tcp

# 开放端口、移除端口后,都要重启防火墙才生效
# 开放端口
firewall-cmd --zone=public --add-port=8080/tcp --permanent
# 移除端口
firewall-cmd  --zone=public --remove-port=8080/tcp --permanent

# 命令含义:
firwall-cmd	# 是Linux提供的操作firewall的一个工具
--zone # 作用域
--add-port=8080/tcp	# 添加端口,格式为:端口/通讯协议
--permanent	# 永久生效,没有此参数重启后失效

下面使用4种语言实现从MySQL数据库中读取数据到浏览器中显示。

1、Java

1、压缩包安装Tomcat

下载Tomcat的tar.gz压缩包Apache Tomcat® - Apache Tomcat 9 Software Downloads
在这里插入图片描述
apache-tomcat-9.0.46.tar.gz上传到服务器的/opt/school_linux_final_test/java目录下。

[root@wu2 ~]# tar -zxvf /opt/school_linux_final_test/java/apache-tomcat-9.0.46.tar.gz -C /opt/school_linux_final_test/java/
[root@wu2 ~]# vim /etc/profile		# 在最后追加
export PATH=$PATH:/opt/school_linux_final_test/java/apache-tomcat-9.0.46/bin
[root@wu2 ~]# source /etc/profile	# 让配置文件/etc/profile生效

2、rpm安装java1.8

Java SE Development Kit 8 - Downloads
在这里插入图片描述

下载需要登录Oracle官网,即需要账号密码,下面是网上找的账号及密码,亲测有效。
Oracle Account:2696671285@qq.com
Oracle Password:Oracle123

jdk-8u291-linux-x64.rpm上传到服务器的/opt/school_linux_final_test/java目录下。

[root@wu2 ~]# rpm -qa | grep jdk	# 检查是否原先安装过jdk
jdk1.8-1.8.0_291-fcs.x86_64	
[root@wu2 ~]# rpm -e --nodeps jdk1.8-1.8.0_291-fcs.x86_64	# 可以卸载掉原先的jdk
[root@wu2 ~]# rpm -ivh /opt/school_linux_final_test/java/jdk-8u291-linux-x64.rpm 	# rpm安装jdk
[root@wu2 ~]# java -version	# 安装成功
java version "1.8.0_291"
Java(TM) SE Runtime Environment (build 1.8.0_291-b10)
Java HotSpot(TM) 64-Bit Server VM (build 25.291-b10, mixed mode)

[root@wu2 ~]# vim /etc/profile		# 在最后追加
JAVA_HOME=/usr/java/jdk1.8.0_291-amd64
CLASSPATH=%JAVA_HOME%/lib:%JAVA_HOME%/jre/lib
PATH=$PATH:$JAVA_HOME/bin:$JAVA_HOME/jre/bin
export PATH CLASSPATH JAVA_HOME
[root@wu2 ~]# source /etc/profile	# 让配置文件/etc/profile生效

3、在本地(Windows电脑上)用IDEA开发一个能实现从MySQL读取内容并显示在浏览器上的项目

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.58</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

application.properties

# ServerProperties
server.port=8080

# ThymeleafProperties
spring.thymeleaf.cache=true

# DataSourceProperties
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/linux_test?characterEncoding=utf-8&useSSL=false&serverTimezone=Hongkong
spring.datasource.username=root
spring.datasource.password=a1b2c3
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.hikari.maximum-pool-size=15
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.idle-timeout=30000

# MybatisProperties
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.example.entity
mybatis.configuration.useGeneratedKeys=true
mybatis.configuration.mapUnderscoreToCamelCase=true

Student.java

public class Student {
    private Integer id;
    private String studentId;
    private String studentName;

	//get和set方法
}

StudentMapper.java

@Mapper
@Repository
public interface StudentMapper {
    List<Student> selectStudents();
}

student-mapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.dao.StudentMapper">

    <sql id="selectFields">
        id, student_id,student_name
    </sql>

    <select id="selectStudents" resultType="Student">
        select <include refid="selectFields"></include>
        from student
    </select>

</mapper>

StudentService.java

@Service
public class StudentService {

    @Autowired
    private StudentMapper studentMapper;

    public List<Student> selectStudents() {
        return studentMapper.selectStudents();
    }
}

StudentController.java

@Controller
public class StudentController {

    @Autowired
    private StudentService studentService;

    @RequestMapping(path = "/", method = RequestMethod.GET)
    //@ResponseBody
    public void /*List<Student>*/ selectStudents(HttpServletResponse response) {
        //return studentService.selectStudents();
        //使用注释掉的代码会产生问题:@ResponseBody返回JSON数据,360安全浏览器弹出下载页面_夜中听雪的博客-CSDN博客  https://blog.csdn.net/wpw2000/article/details/117430507?spm=1001.2014.3001.5502
        response.setContentType("text/html;charset=utf-8");
        try (
                PrintWriter writer = response.getWriter();
        ) {
            writer.write(JSON.toJSONString(studentService.selectStudents()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

DemoApplication.java

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

4、把本地(Windows电脑上)可以访问的SpringBoot项目部署到服务器的Tomcat上

1、修改application.properties

# DataSourceProperties	# 因为访问的是你自己电脑上的mysql->服务器的mysql,可能两个mysql你设置的用户名密码不一致。
# 如:Windows电脑的MySQL密码:a1b2c3。Linux服务器上的MySQL密码:Nowcoder_123。
spring.datasource.username=root
spring.datasource.password=Nowcoder_123

2、修改pom.xml,增加<packaging><finalName>两行

	<name>community</name>
	<description>nowcoder community</description>
	<packaging>war</packaging>

	<build>
		<finalName>ROOT</finalName>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

3、增加一个类:CommunityServletInitializer

package com.example;

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

public class CommunityServletInitializer extends SpringBootServletInitializer {

    //tomcat访问该方法作为入口来运行该项目
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(DemoApplication.class); //这里指出该项目的main方法所在的类
    }
}

4、用maven把项目编译并且打包
在这里插入图片描述

5、shutdown.sh关闭服务器tomcat,删除服务器tomcat的webapp目录下的所有文件。把本地项目目录的target目录下的ROOT.war文件上传到服务器tomcat的webapp目录下。startup.sh开启服务器tomcat。

6、此时,可以使用http://120.79.212.4:8080/访问项目。

5、配置Nginx

[root@wu2 ~]# vim /etc/nginx/nginx.conf	# 增加下方内容
        location /index.java {
        		# 注意:下方的端口号后要加"/",不然会404,因为程序的Controller里是`path = "/"`。
                proxy_pass   http://127.0.0.1:8080/;
        }

[root@wu2 ~]# service nginx restart

此时,可以用 http://120.79.212.4/index.java 访问网页。
在这里插入图片描述

遇到的问题和解决方法

1、
问题:Windows上访问都没有问题,但部署到服务器后,@ResponseBody返回JSON数据,chrome浏览器显示网页,但360安全浏览器弹出下载页面。

解决方法:不使用@ResponseBody注解,而是通过response.getWriter()直接往浏览器写入JSON数据。

具体可以看我的这篇博客:@ResponseBody返回JSON数据,360安全浏览器弹出下载页面_夜中听雪的博客-CSDN博客

2、
问题:nginx的配置问题,无法通过http://120.79.212.4/index.java访问到Java。

解决方法:端口号后要加"/",像这样:proxy_pass http://127.0.0.1:8080/;。不然会404,因为程序的Controller里是path = "/"

2、PHP

1、PHP 的 安装、配置、启动

[root@wu2 ~]# cd /opt/school_linux_final_test/php
[root@wu2 php]# wget https://www.php.net/distributions/php-7.4.5.tar.gz
[root@wu2 php]# yum install -y gcc gcc-c++ make zlib zlib-devel pcre pcre-devel libjpeg libjpeg-devel libpng libpng-devel freetype freetype-devel libxml2 libxml2-devel glibc glibc-devel glib2 glib2-devel bzip2 bzip2-devel ncurses ncurses-devel curl curl-devel e2fsprogs e2fsprogs-devel krb5 krb5-devel openssl openssl-devel openldap openldap-devel nss_ldap openldap-clients openldap-servers libsqlite3x-devel oniguruma-devel
[root@wu2 php]# tar -zxvf php-7.4.5.tar.gz
[root@wu2 php]# cd php-7.4.5
[root@wu2 php-7.4.5]# ./configure --prefix=/usr/local/php --with-config-file-path=/usr/local/php --enable-mbstring --enable-ftp --enable-gd --with-mysqli=mysqlnd --with-pdo-mysql=mysqlnd --without-pear --disable-phar --enable-sockets --with-zlib --with-xmlrpc --enable-fpm --enable-xml --enable-sockets --with-zlib --with-iconv --enable-soap --enable-pcntl --enable-cli --with-curl
[root@wu2 php-7.4.5]# make
[root@wu2 php-7.4.5]# make install
[root@wu2 php-7.4.5]# cp php.ini-production /usr/local/php/php.ini
[root@wu2 php-7.4.5]# vim /usr/local/php/php.ini
display_errors = On	# Off改为On。设置让PHP错误信息打印在页面上。

[root@wu2 php-7.4.5]# cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm
[root@wu2 php-7.4.5]# ll /etc/init.d/php-fpm
-rw-r--r-- 1 root root 2401 Jun  6 20:27 /etc/init.d/php-fpm
[root@wu2 php-7.4.5]# chmod +x /etc/init.d/php-fpm

[root@wu2 php-7.4.5]# cd /usr/local/php/etc
[root@wu2 etc]# cp php-fpm.conf.default php-fpm.conf
[root@wu2 etc]# vi php-fpm.conf
# 去掉 ";pid = run/php-fpm.pid" 前面的分号

[root@wu2 etc]# cd php-fpm.d
[root@wu2 php-fpm.d]# cp www.conf.default www.conf
[root@wu2 php-fpm.d]# vi www.conf	# 修改user和group为php。
user = php
group = php

[root@wu2 php-fpm.d]# groupadd php
[root@wu2 php-fpm.d]# useradd -r -g php php
[root@wu2 php-fpm.d]# chkconfig php-fpm on	# 设置开启启动

[root@wu2 ~]# /etc/init.d/php-fpm start
Starting php-fpm  done
[root@wu2 ~]# ps -ef |grep php
root     25243     1  0 23:35 ?        00:00:00 php-fpm: master process (/usr/local/php/etc/php-fpm.conf)
php      25244 25243  0 23:35 ?        00:00:00 php-fpm: pool www
php      25245 25243  0 23:35 ?        00:00:00 php-fpm: pool www
root     25250 25051  0 23:35 pts/0    00:00:00 grep --color=auto php

2、配置Nginx,测试访问PHP

配置前,ipip/index.htmlip/index.php 都是访问不到页面的。

[root@wu2 ~]# vim /usr/share/nginx/html/index.php	# 写入如下内容
<?php
    phpinfo();
?>

[root@wu2 ~]# vim /etc/nginx/nginx.conf	# 添加的两部分内容被"# my start"和"# my end"框了起来。
        location / {
# my start
                root /usr/share/nginx/html;
                index index.php;
# my end
        }

# my start
        location ~ \.php$ {
                #root           html;
                root   /usr/share/nginx/html;
                fastcgi_pass   127.0.0.1:9000;  #php-fpm默认的端口是9000
                fastcgi_index  index.php;
                fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
                include        fastcgi_params;
         }
# my end

[root@wu2 ~]# service nginx restart
Redirecting to /bin/systemctl restart nginx.service

配置后,ip/index.php 可以访问到下方页面。
在这里插入图片描述
配置后,ipip/index.html 可以访问到下方页面。
在这里插入图片描述

Nginx 之 fastcgi配置 - 简书

3、用PHP语言,实现从MySQL读取内容并显示在浏览器上

[root@wu2 ~]# vim /usr/share/nginx/html/index.php	# 删除原先内容,改为以下内容。
<?php
$mysql_server_name = '127.0.0.1'; // ip
$mysql_username = 'root';         // username
$mysql_password = 'Nowcoder_123'; // password
$mysql_database = 'linux_test';   // database

$conn=mysqli_connect($mysql_server_name,$mysql_username,$mysql_password,$mysql_database); //连接数据库
if ($conn -> connect_errno) {
    printf("Connect failed: %s\n", $conn->connect_error);
    exit();
}
//查询
$sql = "select * from student";
$query = $conn->query($sql);

//设置客户端响应头。不设也是显示网页。
//header('Content-Type:text/html;charset=utf-8');

echo "这是PHP实现的页面";
//构造表头
echo "<table border='1'><tr>";
echo "<th>id</th>";
echo "<th>学号</th>";
echo "<th>姓名</th>";
echo "</tr>";
//遍历输出
while($row = $query->fetch_array()){
	echo "<tr>";
    echo "<td>".$row['id']."</td>";
	echo "<td>".$row['student_id']."</td>";
	echo "<td>".$row['student_name']."</td>";
	echo "</tr>";
}
//释放结果集+关闭MySQL连接
$query -> free_result();
$conn -> close();
?>

访问http://120.79.212.4/index.php时:
在这里插入图片描述

遇到的问题和解决方法

1、
问题:访问http://120.79.212.4/index.php时报错:Warning: mysqli_connect(): (HY000/2002): No such file or directory in /usr/share/nginx/html/index.php on line 7

解决方法:把$mysql_server_name = 'localhost';改为$mysql_server_name = '127.0.0.1';

2、
问题:访问http://120.79.212.4/index.php时报错:Warning: mysqli_connect(): The server requested authentication method unknown to the client [caching_sha2_password] in /usr/share/nginx/html/index.php on line 7

原因:php还不支持mysql8.0最新的密码加密方式。

解决方法:

[root@wu2 ~]# mysql -uroot -p
Enter password: 
mysql> use mysql;
mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'Nowcoder_123';
mysql> exit
[root@wu2 ~]# service mysqld restart
Redirecting to /bin/systemctl restart mysqld.service

小知识:php命令:启动、停止、重启。

/etc/init.d/php-fpm start # php-fpm启动命令
/etc/init.d/php-fpm stop  # php-fpm停止命令
/etc/init.d/php-fpm restart # php-fpm重启命令
ps -ef | grep php  # 查看是否已经成功启动PHP

3、Go

1、Golang的安装,第一个Go程序

[root@wu2 ~]# yum list golang*
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
Available Packages
golang.x86_64                                                             1.15.5-1.el7                         epel
。。。
[root@wu2 ~]# yum install -y golang.x86_64
[root@wu2 ~]# go version
go version go1.15.5 linux/amd64

[root@wu2 ~]# mkdir -p /root/myLinuxTest/go/src /root/myLinuxTest/go/bin /root/myLinuxTest/go/pkg

[root@wu2 ~]# vim /etc/profile	# 增加两句。配置环境变量。
export GOROOT=/usr/lib/golang
export GOPATH=/root/myLinuxTest/go
[root@wu2 ~]# source /etc/profile	# 让文件生效

[root@wu2 ~]# mkdir -p /root/myLinuxTest/go/src/hello
[root@wu2 ~]# vim /root/myLinuxTest/go/src/hello/hello.go	# 写入如下内容
package main
import "fmt"
func main() {
    fmt.Printf("hello world\n")
}
[root@wu2 ~]# go run /root/myLinuxTest/go/src/hello/hello.go 	# 运行hello.go
hello world

2、用Go语言搭建简单的web服务器,即实现在浏览器上显示内容

[root@wu2 ~]# vim /root/myLinuxTest/go/src/hello/http2.go	# 写入下方代码
package main

import (
    "io"
    "net/http"
    "fmt"
)

func hello(w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, "Hello world!")
    fmt.Fprintf(w, "Hello Wrold on client!") //这个写入到w的是输出到客户端的
    fmt.Println("Hello Wrold on console!")
}

func main() {
    http.HandleFunc("/", hello)
    
    // 默认为127.0.0.1。运行后,只能在本机用"127.0.0.1:8000"访问,无法用"http://120.79.212.4:8000/"从其他电脑上访问
    http.ListenAndServe(":8000", nil)  
}

运行web服务,并访问。

[root@wu2 ~]# go run /root/myLinuxTest/go/src/hello/http2.go	# 运行
Hello Wrold on console!

在这里插入图片描述

如果无法用浏览器访问,进行如下操作。

# 如果无法用浏览器访问,进行如下操作。
[root@wu2 ~]# ps -ef |grep go	# 确定有该进程
root     18305  9950  0 16:54 pts/1    00:00:00 go run /root/myLinuxTest/go/src/hello/http2.go
root     18345 18305  0 16:54 pts/1    00:00:00 /tmp/go-build045791547/b001/exe/http2
root     18477 12619  0 16:57 pts/2    00:00:00 grep --color=auto go
[root@wu2 ~]# netstat -ntlp | grep 8000	# 查看8000端口是否打开
tcp6       0      0 :::8000                 :::*                    LISTEN      18345/http2         
[root@wu2 ~]# curl 127.0.0.1:8000	# curl命令会把网页的html都打印出来。用该命令确认本机能够访问该web服务。
Hello world!Hello Wrold on client!
# 本机能访问,外部无法访问时,打开阿里云安全组的相应端口和防火墙上的相应端口。
# 下面是打开防火墙端口的。
[root@wu2 ~]# firewall-cmd --zone=public --add-port=8000/tcp --permanent	# 开放防火墙端口
[root@wu2 ~]# service firewalld restart	# 开放端口、移除端口后,都要重启防火墙才生效

curl 的用法指南 - 阮一峰的网络日志:curl 是常用的命令行工具,用来请求 Web 服务器。它的名字就是客户端(client)的 URL 工具的意思。

3、用Go语言,实现从MySQL读取内容并显示在浏览器上

[root@wu2 ~]# go get github.com/go-sql-driver/mysql		# 下载驱动包
[root@wu2 ~]# vim /root/myLinuxTest/go/src/hello/student.go	# 写入如下内容
package main
import (
    "fmt"
    "net/http"
    "log"
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
)
func all(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "text/html;charset=utf-8")
	fmt.Fprintf(w,"这是Golang实现的页面")
	//链接数据库
	//用户名:密码@tcp(127.0.0.1:3306)/数据库名
	db, err := sql.Open("mysql", "root:Nowcoder_123@tcp(127.0.0.1:3306)/linux_test")
	if err != nil {
    		log.Fatal(err)
	}
	defer db.Close()
	//查询
	rows, err := db.Query("SELECT * FROM student")
	if err != nil {
    		log.Fatal(err)
	}
	defer rows.Close()
	//建立表头
	fmt.Fprintf(w,"<table border='1'><tr>")
	fmt.Fprintf(w,"<th>id</th>")
	fmt.Fprintf(w,"<th>学号</th>")
	fmt.Fprintf(w,"<th>姓名</th>")
	fmt.Fprintf(w,"</tr>")
	//遍历结果集
	for rows.Next() {
    	var id int
		var student_id string
		var student_name string
    		if err := rows.Scan(&id,&student_id,&student_name); err != nil {
        			log.Fatal(err)
    		}
   		fmt.Fprintf(w,"<tr>")
		fmt.Fprintf(w,"<td>%d</td>",id)
		fmt.Fprintf(w,"<td>%s</td>",student_id)
		fmt.Fprintf(w,"<td>%s</td>",student_name)
		fmt.Fprintf(w,"</tr>")
	}
	if err := rows.Err(); err != nil {
    		log.Fatal(err)
	}
}
func main() {
	//设置访问的路由
    http.HandleFunc("/",all) 
    //设置监听的端口
    err := http.ListenAndServe(":8000", nil)
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}
# 下方两种运行方式,选一种就可以
[root@wu2 ~]# go run /root/myLinuxTest/go/src/hello/student.go				# 前台暂时运行
[root@wu2 ~]# nohup go run /root/myLinuxTest/go/src/hello/student.go &		# 后台长期运行

此时,可以用 http://120.79.212.4:8000/ 访问。

4、配置Nginx

[root@wu2 ~]# vim /etc/nginx/nginx.conf	# 增加下方配置。使得访问 "ip/xxx.go" 可以访问到 "http://120.79.212.4:8000/"
        location ~ \.go$ {
                proxy_pass   http://127.0.0.1:8000;
        }
[root@wu2 ~]# service nginx restart

此时,可以用 http://120.79.212.4/index.go 访问。
在这里插入图片描述

4、Nodejs

1、安装Nodejs

[root@wu2 ~]# yum list node*
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
Available Packages
node-gyp.noarch                                    0.10.6-2.el7               epel
nodejs.x86_64                                      1:6.17.1-1.el7             epel
[root@wu2 ~]# yum install -y nodejs.x86_64
[root@wu2 ~]# node -v
v6.17.1

2、Nodejs访问数据库

[root@wu2 ~]# cd /root/myLinuxTest/nodejs
[root@wu2 nodejs]# npm install mysql
[root@wu2 nodejs]# vim /root/myLinuxTest/nodejs/all.js	# 文件写入如下内容
var mysql  = require('mysql');
//创建连接
var connection = mysql.createConnection({    
  host     : 'localhost',
  user     : 'root',    
  password : 'Nowcoder_123',
  port     : '3306',    
  database : 'linux_test'
});
//连接
connection.connect();

var sql = 'select * from student';
//开始查询
connection.query(sql,function(err,result){
        if(err){
                console.log('[select error] -',err.message);
                return;
        }   
        console.log(result);
});
connection.end();
[root@wu2 nodejs]# node /root/myLinuxTest/nodejs/all.js	# 运行
[ RowDataPacket { id: 1, student_id: '2018xxxxxxxx', student_name: 'xxx' },
  RowDataPacket { id: 2, student_id: '1111', student_name: '其他学生' } ]

3、用Nodejs语言,实现从MySQL读取内容并显示在浏览器上

[root@wu2 ~]# vim /root/myLinuxTest/nodejs/index.js
var http=require('http');
var url = require('url');
var mysql  = require('mysql');
//创建连接
var connection = mysql.createConnection({    
	host     : 'localhost',
	user     : 'root',    
	password : 'Nowcoder_123',
	port     : '3306',    
	database : 'linux_test'
});
//准备sql
var sql = 'select * from student';

//创建服务器
server = http.createServer(function(request,response) {
/*
	//解析请求,包括文件名
	var pathname= url.parse(request.url).pathname;
	//console.log(pathname);
	if(pathname !="/index.js"){
		//HTTP 状态码 404 : NOT FOUND。Content Type:text/plain
		response.writeHead(404,{'Content-Type': 'text/html'});
		response.end("<p1>error</p1>");
		return;
	}   
*/
	//HTTP 状态码 200 : OK。Content Type:text/plain
	response.writeHead(200,{'Content-Type': 'text/html'});
	//向客户端输出
	//开始查询
	connection.query(sql,function(err,result){
        if(err){
                console.log('[select error] -',err.message);
                return;
        }
        //console.log(result);
        response.write(
        '<!DOCTYPE html>'+
        '<html lang="en">'+
        '<head>'+
        '<meta charset="utf-8"/>'+
        '</head>');
        response.write("这是Nodejs实现的页面");
        //打印表头
        response.write("<table border='1'><tr>");
        response.write("<th>id</th>");
        response.write("<th>学号</th>");
        response.write("<th>姓名</th></tr>");

        //遍历结果集输出
        result.forEach(r =>{
                response.write("<tr>");
                response.write("<td>"+r.id+"</td>");
                response.write("<td>"+r.student_id+"</td>");
                response.write("<td>"+r.student_name+"</td>");
                response.write("</tr>");
		})
	//发送响应数据
	response.end();
	});
});
server.listen(8001);
# 下方两种运行方式,选一种就可以

[root@wu2 ~]# node /root/myLinuxTest/nodejs/index.js	# 前台临时运行

# 后台长期运行。使用forever来使得:nodejs 在linux上后台运行。XShell链接断开后,这个index.js程序还能运行。
[root@wu2 ~]# npm install -g forever	# -g 的意思是将模块安装到全局,具体安装到磁盘哪个位置,要看 npm config prefix 的位置。
[root@wu2 ~]# forever start /root/myLinuxTest/nodejs/index.js

此时,可以用 http://120.79.212.4:8001/ 访问。

4、配置Nginx

[root@wu2 ~]# vim /etc/nginx/nginx.conf	# 增加下方配置。使得访问 "ip/xxx.js" 可以访问到 "http://120.79.212.4:8001/"

        location ~/index.js$ {
                proxy_pass   http://127.0.0.1:8001;
        }
[root@wu2 ~]# service nginx restart

此时,可以用 http://120.79.212.4/index.js 访问。
在这里插入图片描述

其他

1、系统架构图

Java
在这里插入图片描述

PHP
在这里插入图片描述

Go
在这里插入图片描述

Nodejs
在这里插入图片描述

2、系统相关信息

系统发行版信息

阿里云服务器,2核4GiB,ecs.s6-c1m2.large ,华南1(深圳),深圳可用区D,CentOS7.7,64位,2021年6月30日过期。
在这里插入图片描述

系统IP信息

在这里插入图片描述

3、软件和语言的版本信息

Windows上:
IDE: IntelliJ IDEA 2020.2.3 x64

Linux服务器上:

System: CentOS7.7
Database: MySQL 8.0.25
Nginx:nginx/1.16.1

JDK: jdk1.8-1.8.0_291
Tomcat: apache-tomcat-9.0.46
PHP: php-7.4.5
Go: go1.15.5 linux/amd64
Nodejs: v6.17.1

4、其他的 遇到的问题和解决方法

1、
可以直接wget http://...这样把压缩包、rpm包直接下载到服务器上。但不知道为什么非常慢,大概每秒十几kb。所以相比起来,下载到本机,再用Xftp上传到服务器会快很多。

wget https://www.php.net/distributions/php-7.4.5.tar.gz

2、
想要维持一个长期后台运行的 logstash,你需要同时在命令前面加 nohup,后面加 &。
注意:后面加&时,需要先空上一格,再写&。不过不空格也没有什么事情。

# go程序使用这种方式没有问题,在XShell链接断开后,这个go程序还能够运行。
[root@wu2 ~]# nohup go run /root/myLinuxTest/go/src/hello/student.go &	
# nodejs程序使用这种方式有问题,在XShell链接断开后,过上一会儿,这个index.js程序也不运行了。
[root@wu2 ~]# nohup node /root/myLinuxTest/nodejs/index.js &		

# 所以,使用forever来使得:nodejs 在linux上后台运行。XShell链接断开后,这个index.js程序还能运行。
[root@wu2 ~]# npm install -g forever	# -g 的意思是将模块安装到全局,具体安装到磁盘哪个位置,要看 npm config prefix 的位置。
[root@wu2 ~]# forever start /root/myLinuxTest/nodejs/index.js

可以通过ps命令查看进程是否启动。

[root@wu2 ~]# ps -ef |grep go
[root@wu2 ~]# ps -ef |grep node

5、总结

1、我把软件安装在/opt/school_linux_final_test下,把程序代码放在/root/myLinuxTest下。这两个文件夹下都有4个子文件夹:java、php、go、nodejs。

6、参考

Linux安装php+nginx并访问数据库+部署到web_LittleSeedling的博客-CSDN博客

Linux安装Golang并访问数据库+部署到web_LittleSeedling的博客-CSDN博客

Linux安装Nodejs并访问数据库+部署到web_LittleSeedling的博客-CSDN博客

  • 22
    点赞
  • 71
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
好的,我了解了你的问题。下面是我对这个问题的回答: 首先,我们安装 Docker 和 Docker Compose 工具。里就不详细介绍了,可以参考方文档进行安装。 接下来,我们可以使用 Docker Compose 编写一个 docker-compose.yml,来定义我们的应用程序和服务。 下面是一个示例 docker-compose.yml 文件,它定义了一个 PHPMySQL 和 Nginx 服务: ``` version: '3' services: php: build: ./php volumes: - ./php:/var/www/html depends_on - db db: image: mysql:5.7 environment: MYSQL_ROOT_PASSWORD: root MYSQL_DATABASE: test volumes: - ./mysql:/var/lib/mysql web: image: nginx volumes: - ./nginx:/etc/nginx/conf.d - ./php:/var/www/html ports: - "80:80" depends_on: - php ``` 在上面的配置中,我们定义了三个服务,即 PHPMySQL 和 Nginx。其中,PHP 服务使用了一个名为 ./php 的 Docker 镜像,MySQL 服务使用了官方的 MySQL 5.7 镜像,Nginx 服务使用了官方的 Nginx 镜像。 接下来,我们可以在 ./php 目录下创建一个 index.php 文件,来实现MySQL 数据库中读取数据并在网页中显示。下面是一个示例代码: ```php <?php $host = 'db'; $user = 'root'; $password = 'root'; $dbname = 'test'; $conn = new mysqli($host, $user, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT * FROM users"; $result = $conn->query($sql); if ($result->num_rows > 0) { echo "<table><tr><th>ID</th><th>Name</th></tr>"; while($row = $result->fetch_assoc()) { echo "<tr><td>" . $row["id"] . "</td><td>" . $row["name"] . "</td></tr>"; } echo "</table>"; } else { echo "0 results"; } $conn->close(); ?> ``` 最后,我们可以使用 docker-compose 命令来启动这个应用程序: ``` docker-compose up -d ``` 这个命令会在后台启动所有的服务,并将它们连接起来。在浏览器中访问 http://localhost,就可以看到从 MySQL 数据库中读取的数据了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值