CentOS Stream 如何替代 RHEL 进行高效开发与测试的完整指南

引言:理解 CentOS Stream 与 RHEL 的关系
CentOS Stream 是一个创新性的 Linux 发行版,它位于 Fedora(上游开发版)和 RHEL(企业版)之间,为开发者提供了一个持续集成的平台。随着 CentOS 项目的重大调整,了解如何有效利用 CentOS Stream 作为 RHEL 的开发和测试替代方案变得至关重要。
为什么选择 CentOS Stream?
持续更新
:提供比 RHEL 更新的软件包,同时保持与 RHEL 的高度兼容性
前瞻性开发
:可以提前接触到即将进入 RHEL 的功能和更新
社区驱动
:完全开源,开发者可以参与功能开发和问题修复
零成本
:完全免费,适合个人开发者和小型团队
系统安装与基础配置
1. 下载与安装 CentOS Stream
访问
CentOS Stream 官方网站
下载最新版本的 ISO 镜像。推荐使用 CentOS Stream 9,因为它与 RHEL 9 保持同步。
# 验证下载的 ISO 文件完整性
sha256sum CentOS-Stream-9-latest-x86_64-dvd1.iso

# 创建可启动 USB(Linux/macOS)
sudo dd if=CentOS-Stream-9-latest-x86_64-dvd1.iso of=/dev/sdX bs=4M status=progress
2. 最小化安装后的初始配置
# 更新系统到最新状态
sudo dnf update -y

# 安装 EPEL 仓库(额外软件包)
sudo dnf install epel-release -y

# 安装基础开发工具
sudo dnf groupinstall “Development Tools” -y

# 安装常用工具
sudo dnf install vim git curl wget tmux htop tree -y

# 配置防火墙(如果需要)
sudo systemctl enable firewalld
sudo systemctl start firewalld
sudo firewall-cmd –permanent –add-service=ssh
sudo firewall-cmd –reload
3. 配置系统环境
# 创建开发用户(建议不要使用 root)
sudo useradd -m -s /bin/bash developer
sudo passwd developer
sudo usermod -aG wheel developer

# 配置 sudo 权限(编辑 /etc/sudoers)
sudo visudo
# 取消注释:%wheel ALL=(ALL) NOPASSWD: ALL

# 配置 SSH 密钥登录(可选但推荐)
sudo systemctl enable sshd
sudo systemctl start sshd
开发环境搭建
1. 安装编程语言环境
Python 开发环境
# 安装 Python 3.9 和开发包
sudo dnf install python3 python3-devel python3-pip -y

# 安装虚拟环境工具
python3 -m pip install –user virtualenv

# 创建虚拟环境示例
mkdir ~/projects/myapp
cd ~/projects/myapp
python3 -m venv venv
source venv/bin/activate

# 安装常用 Python 包
pip install flask django requests pytest
Node.js 开发环境
# 安装 Node.js 16(CentOS Stream 9 默认提供)
sudo dnf module install nodejs:16 -y

# 或者使用 NodeSource 仓库安装更新版本
curl -fsSL https://rpm.nodesource.com/setup_18.x | sudo bash –
sudo dnf install nodejs -y

# 验证安装
node –version
npm –version

# 全局安装常用工具
npm install -g @vue/cli create-react-app
Java 开发环境
# 安装 OpenJDK 11 和 17
sudo dnf install java-11-openjdk-devel java-17-openjdk-devel -y

# 配置 Java 版本切换
sudo alternatives –config java

# 安装 Maven
sudo dnf install maven -y

# 验证
mvn –version
2. 容器化开发环境
Podman 安装与配置(推荐替代 Docker)
# 安装 Podman
sudo dnf install podman podman-docker -y

# 配置无 root 运行
sudo systemctl –user enable podman.socket
sudo systemctl –user start podman.socket

# 测试 Podman
podman run hello-world

# 创建开发容器示例
podman run -it –name dev-container \
-v ~/projects:/workspace \
-p 8080:8080 \
centos:stream9 /bin/bash

# 在容器内安装开发工具
dnf install vim git curl -y
Docker 安装(如果需要)
# 安装 Docker CE
sudo dnf config-manager –add-repo https://download.docker.com/linux/centos/docker-ce.repo
sudo dnf install docker-ce docker-ce-cli containerd.io -y

# 启动 Docker 服务
sudo systemctl enable docker
sudo systemctl start docker

# 将用户添加到 docker 组
sudo usermod -aG docker $USER
# 需要重新登录生效
3. 数据库环境配置
PostgreSQL
# 安装 PostgreSQL 13
sudo dnf install postgresql-server postgresql-contrib -y

# 初始化数据库
sudo postgresql-setup –initdb

# 配置访问权限
sudo vi /var/lib/pgsql/data/pg_hba.conf
# 修改为:host all all 127.0.0.1/32 md5

# 启动服务
sudo systemctl enable postgresql
sudo systemctl start postgresql

# 创建开发数据库和用户
sudo -u postgres psql
CREATE DATABASE devdb;
CREATE USER devuser WITH PASSWORD ‘devpass’;
GRANT ALL PRIVILEGES ON DATABASE devdb TO devuser;
\q
MySQL/MariaDB
# 安装 MariaDB
sudo dnf install mariadb-server mariadb -y

# 启动服务
sudo systemctl enable mariadb
sudo systemctl start mariadb

# 安全配置
sudo mysql_secure_installation

# 创建开发数据库
sudo mysql -u root -p
CREATE DATABASE devdb;
CREATE USER ‘devuser’@’localhost’ IDENTIFIED BY ‘devpass’;
GRANT ALL PRIVILEGES ON devdb.* TO ‘devuser’@’localhost’;
FLUSH PRIVILEGES;
EXIT;
高效开发工作流
1. 使用 IDE 和编辑器
VS Code 远程开发配置
# 安装 VS Code 服务器依赖
sudo dnf install libx11-xcb libxkbfile -y

# 在本地机器上,使用 VS Code 的 Remote-SSH 扩展连接到 CentOS Stream
# 或者使用 VS Code Remote Containers 连接到开发容器

# 安装开发扩展(在 VS Code 中)
# – Python
# – ESLint
# – Docker
# – Remote – SSH
Vim/Neovim 配置
# 安装 Neovim
sudo dnf install neovim -y

# 配置开发环境
mkdir -p ~/.config/nvim
cat > ~/.config/nvim/init.vim << 'EOF' set number set tabstop=4 set shiftwidth=4 set expandtab set autoindent set smartindent syntax on EOF # 安装插件管理器(可选) sh -c 'curl -fLo "${XDG_DATA_HOME:-$HOME/.local/share}"/nvim/site/autoload/plug.vim --create-dirs \ https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim' 2. 版本控制工作流 Git 配置与最佳实践 # 配置 Git git config --global user.name "Your Name" git config --global user.email "your.email@example.com" git config --global init.defaultBranch main # 配置 SSH 密钥(如果使用 SSH) ssh-keygen -t ed25519 -C "your.email@example.com" cat ~/.ssh/id_ed25519.pub # 将公钥添加到 GitHub/GitLab # 创建示例项目 mkdir ~/projects/demo-app cd ~/projects/demo-app git init echo "# Demo App" > README.md
git add README.md
git commit -m “Initial commit”

# 配置 .gitignore
cat > .gitignore << 'EOF' __pycache__/ *.pyc .env venv/ node_modules/ dist/ build/ EOF 3. 调试与测试环境 Python 调试环境 # 安装调试工具 python3 -m pip install debugpy # VS Code 调试配置(.vscode/launch.json) cat > .vscode/launch.json << 'EOF' { "version": "0.2.0", "configurations": [ { "name": "Python: Current File", "type": "python", "request": "launch", "program": "${file}", "console": "integratedTerminal", "justMyCode": true } ] } EOF # 使用 debugpy 远程调试 # 在代码中添加: import debugpy debugpy.listen(('0.0.0.0', 5678)) debugpy.wait_for_client() Node.js 调试 # 启用 Node.js 调试 node --inspect=0.0.0.0:9229 app.js # 或者使用 Chrome DevTools 连接 # 在 Chrome 中打开 chrome://inspect 测试环境配置 1. 单元测试环境 Python 单元测试 # 安装测试框架 python3 -m pip install pytest pytest-cov pytest-mock # 创建测试目录结构 mkdir -p tests/unit cat > tests/unit/test_app.py << 'EOF' import pytest from app import create_app @pytest.fixture def client(): app = create_app() app.config['TESTING'] = True with app.test_client() as client: yield client def test_home_page(client): rv = client.get('/') assert rv.status_code == 200 assert b'Hello' in rv.data EOF # 运行测试 pytest tests/unit/test_app.py --cov=app --cov-report=html JavaScript 单元测试 # 安装 Jest npm install --save-dev jest @types/jest # 配置 package.json cat > package.json << 'EOF' { "scripts": { "test": "jest", "test:coverage": "jest --coverage" }, "jest": { "testEnvironment": "node", "coveragePathIgnorePatterns": ["/node_modules/"] } } EOF # 创建测试文件 cat > tests/app.test.js << 'EOF' const { sum } = require('../app'); test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
EOF

# 运行测试
npm test
2. 集成测试环境
使用 Docker Compose 创建测试环境
# 安装 Docker Compose
sudo dnf install docker-compose -y

# 创建 docker-compose.yml
cat > docker-compose.yml << 'EOF' version: '3.8' services: web: build: . ports: - "8080:8080" depends_on: - db environment: - DATABASE_URL=postgresql://devuser:devpass@db:5432/devdb db: image: postgres:13 environment: - POSTGRES_DB=devdb - POSTGRES_USER=devuser - POSTGRES_PASSWORD=devpass volumes: - postgres_data:/var/lib/postgresql/data redis: image: redis:6-alpine volumes: postgres_data: EOF # 创建 Dockerfile cat > Dockerfile << 'EOF' FROM python:3.9-slim WORKDIR /app COPY requirements.txt . RUN pip install -r requirements.txt COPY . . CMD ["python", "app.py"] EOF # 启动测试环境 docker-compose up -d # 查看日志 docker-compose logs -f # 运行集成测试 docker-compose exec web pytest tests/integration/ 3. 性能测试环境 使用 Locust 进行负载测试 # 安装 Locust python3 -m pip install locust # 创建测试脚本 cat > locustfile.py << 'EOF' from locust import HttpUser, task, between class QuickstartUser(HttpUser): wait_time = between(1, 2.5) @task def hello_world(self): self.client.get("/") @task(3) def view_item(self): for item_id in range(10): self.client.get(f"/item?id={item_id}", name="/item") EOF # 启动 Locust(在 CentOS Stream 上) locust -f locustfile.py --host=http://localhost:8080 # 在浏览器中访问 http://localhost:8089 进行测试 与 RHEL 的兼容性保证 1. 源代码级别的兼容性 CentOS Stream 与 RHEL 在源代码级别保持高度一致。关键差异在于: 更新节奏 :CentOS Stream 接收更新比 RHEL 早 2-6 周 功能预览 :新功能首先在 CentOS Stream 中测试 ABI 兼容性 :保持二进制兼容性,确保应用可以无缝迁移 2. 使用 Mock 构建 RHEL 兼容包 # 安装 Mock 构建系统 sudo dnf install mock mock-epel-release -y # 将用户添加到 mock 组 sudo usermod -aG mock $USER # 需要重新登录 # 创建 RHEL 9 兼容的构建配置 cat > ~/rpmbuild/SPECS/myapp.spec << 'EOF' Name: myapp Version: 1.0 Release: 1%{?dist} Summary: My Application License: MIT URL: https://example.com Source0: %{name}-%{version}.tar.gz BuildRequires: python3-devel Requires: python3 %description My application description %prep %setup -q %build %{__python3} setup.py build %install %{__python3} setup.py install --skip-build --root %{buildroot} %files %{_bindir}/myapp %{python3_sitelib}/myapp/ %changelog * Tue Jan 01 2024 Your Name – 1.0-1
– Initial package
EOF

# 构建 RPM 包(使用 RHEL 9 兼容配置)
mock -r rhel-9-x86_64 ~/rpmbuild/SPECS/myapp.spec
3. 使用 Toolbox 进行环境隔离
# 安装 Toolbox
sudo dnf install toolbox -y

# 创建 RHEL 9 兼容的开发容器
toolbox create –distro rhel –release 9

# 进入开发环境
toolbox enter rhel-9

# 在容器内安装开发工具
sudo dnf install gcc make python3-devel -y

# 退出容器
exit

# 查看所有容器
toolbox list

# 删除容器
toolbox rm rhel-9
CI/CD 集成
1. GitLab CI 配置
# 在项目根目录创建 .gitlab-ci.yml
cat > .gitlab-ci.yml << 'EOF' stages: - test - build - deploy variables: DOCKER_DRIVER: overlay2 before_script: - dnf install -y python3 python3-pip git - python3 -m pip install -r requirements.txt test: stage: test script: - pytest tests/ --cov=app --cov-report=xml artifacts: reports: coverage_report: coverage_format: cobertura path: coverage.xml build: stage: build script: - docker build -t $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA . - docker push $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA only: - main deploy: stage: deploy script: - echo "Deploying to production..." # 添加实际的部署命令 only: - main EOF 2. Jenkins Pipeline # 安装 Jenkins sudo dnf install -y java-17-openjdk sudo wget -O /etc/yum.repos.d/jenkins.repo https://pkg.jenkins.io/redhat-stable/jenkins.repo sudo rpm --import https://pkg.jenkins.io/redhat-stable/jenkins.io-2023.key sudo dnf install -y jenkins # 启动 Jenkins sudo systemctl enable jenkins sudo systemctl start jenkins # 创建 Jenkinsfile cat > Jenkinsfile << 'EOF' pipeline { agent any environment { PYTHON_VERSION = '3.9' } stages { stage('Checkout') { steps { checkout scm } } stage('Test') { steps { sh ''' python3 -m venv venv source venv/bin/activate pip install -r requirements.txt pytest tests/ --cov=app ''' } } stage('Build') { steps { sh ''' docker build -t myapp:${BUILD_NUMBER} . ''' } } } } EOF 性能优化技巧 1. 系统性能调优 # 安装性能监控工具 sudo dnf install sysstat perf htop -y # 启用 sysstat 收集 sudo systemctl enable sysstat sudo systemctl start sysstat # 配置内核参数(开发环境优化) sudo sysctl -w net.core.somaxconn=1024 sudo sysctl -w vm.swappiness=10 # 持久化配置 echo "net.core.somaxconn=1024" | sudo tee -a /etc/sysctl.conf echo "vm.swappiness=10" | sudo tee -a /etc/sysctl.conf 2. 开发工具性能优化 # 配置 Bash 加速 cat >> ~/.bashrc << 'EOF' # 加速提示符 export PS1='[\u@\h \W]\$ ' # 历史记录优化 export HISTSIZE=10000 export HISTFILESIZE=20000 export HISTCONTROL=ignoreboth # 别名 alias ll='ls -alF' alias la='ls -A' alias l='ls -CF' EOF # 配置 Git 性能优化 git config --global core.preloadindex true git config --global core.fscache true git config --global gc.auto 256 故障排除与最佳实践 1. 常见问题解决 问题:SELinux 导致权限问题 # 查看 SELinux 状态 sestatus # 临时禁用(不推荐生产环境) sudo setenforce 0 # 检查 SELinux 日志 sudo ausearch -m avc -ts recent # 修复文件上下文 sudo restorecon -Rv /path/to/directory # 创建自定义策略(推荐) sudo ausearch -m avc -ts recent | audit2allow -M myapp sudo semodule -i myapp.pp 问题:防火墙阻止服务访问 # 查看防火墙规则 sudo firewall-cmd --list-all # 添加服务端口 sudo firewall-cmd --permanent --add-port=8080/tcp sudo firewall-cmd --reload # 临时允许(测试用) sudo firewall-cmd --add-port=8080/tcp 2. 日志分析与监控 # 查看系统日志 sudo journalctl -u your-service -f # 查看应用日志 tail -f /var/log/your-app.log # 使用 systemd 监控 sudo systemd-cgtop # 磁盘使用情况 df -h du -sh * | sort -hr 总结 CentOS Stream 作为 RHEL 的上游开发版,为开发者提供了稳定、免费且功能丰富的开发测试环境。通过本文的完整指南,您应该能够: ✅ 正确安装和配置 CentOS Stream ✅ 搭建完整的开发环境(Python、Node.js、Java 等) ✅ 配置容器化开发环境 ✅ 建立高效的测试工作流 ✅ 确保与 RHEL 的兼容性 ✅ 集成 CI/CD 流程 ✅ 进行性能优化和故障排除 关键要点回顾 持续更新 :利用 CentOS Stream 的新特性,但保持与 RHEL 的兼容性 容器优先 :使用 Podman 和 Toolbox 进行环境隔离 自动化测试 :建立完整的单元测试、集成测试和性能测试体系 CI/CD 集成 :将开发流程自动化,提高效率 性能监控 :持续监控系统性能,及时优化 通过遵循这些最佳实践,您可以充分利用 CentOS Stream 的优势,构建高效、可靠的开发测试环境,同时确保代码可以无缝迁移到 RHEL 生产环境。