1. Vue.js开发环境搭建全攻略
作为前端开发领域最受欢迎的框架之一,Vue.js以其轻量级和渐进式特性赢得了大量开发者的青睐。我刚接触Vue时也曾在环境配置上踩过不少坑,今天就把这些年积累的完整安装方案和避坑经验分享给大家。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 环境准备与工具选型
2.1 Node.js安装与版本管理
Vue CLI需要Node.js运行时环境,建议通过nvm(Node Version Manager)进行安装:
bash复制curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.3/install.sh | bash
安装完成后,选择LTS版本:
bash复制nvm install --lts
nvm use --lts
注意:Windows用户可以使用nvm-windows,但需要以管理员身份运行安装程序
2.2 包管理器选择
根据项目需求选择合适的包管理器:
| 工具 | 特点 | 适用场景 |
|---|---|---|
| npm | Node自带 | 简单项目、快速原型开发 |
| yarn | 速度快、确定性安装 | 大型项目、团队协作 |
| pnpm | 节省磁盘空间 | 多项目开发、CI/CD环境 |
个人推荐使用yarn:
bash复制npm install -g yarn
3. Vue CLI安装与配置
3.1 全局安装Vue CLI
bash复制yarn global add @vue/cli
# 或
npm install -g @vue/cli
验证安装:
bash复制vue --version
3.2 创建新项目
使用交互式命令行创建项目:
bash复制vue create my-project
关键配置选项:
- 选择Manually select features
- 勾选Babel、Router、Vuex等必要功能
- 选择Vue 3版本
- 使用ESLint + Prettier保证代码规范
- 选择In dedicated config files分离配置
3.3 项目结构解析
典型Vue项目目录:
code复制my-project/
├── public/ # 静态资源
├── src/ # 源代码
│ ├── assets/ # 模块资源
│ ├── components/ # 公共组件
│ ├── router/ # 路由配置
│ ├── store/ # Vuex状态管理
│ ├── views/ # 页面组件
│ ├── App.vue # 根组件
│ └── main.js # 入口文件
├── .eslintrc.js # ESLint配置
├── babel.config.js # Babel配置
└── package.json # 项目配置
4. 开发工具配置
4.1 VS Code推荐插件
- Volar - Vue 3官方推荐的语言支持插件
- ESLint - 代码规范检查
- Prettier - 代码格式化
- Vue Peek - 快速跳转定义
- Path Intellisense - 路径自动补全
4.2 浏览器调试工具
安装Vue Devtools浏览器扩展:
- Chrome Web Store搜索"Vue.js devtools"
- 确保启用"允许访问文件网址"
5. 项目优化与最佳实践
5.1 性能优化配置
在vue.config.js中添加:
javascript复制module.exports = {
chainWebpack: config => {
config.optimization.splitChunks({
chunks: 'all',
maxSize: 244 * 1024 // 拆分大文件
})
},
productionSourceMap: false // 关闭sourcemap
}
5.2 环境变量管理
创建.env文件:
code复制VUE_APP_API_URL=https://api.example.com
VUE_APP_DEBUG=true
代码中使用:
javascript复制console.log(process.env.VUE_APP_API_URL)
6. 常见问题解决方案
6.1 安装速度慢问题
- 更换npm镜像源:
bash复制npm config set registry https://registry.npmmirror.com
- 使用yarn的离线模式:
bash复制yarn install --offline
6.2 版本兼容性问题
锁定依赖版本:
json复制{
"resolutions": {
"vue": "3.2.47",
"vue-router": "4.1.6"
}
}
6.3 ESLint报错处理
常见错误及修复:
Missing trailing comma- 在Prettier配置中添加:
json复制{
"trailingComma": "es5"
}
Component name should always be multi-word- 在ESLint规则中禁用:
javascript复制rules: {
'vue/multi-word-component-names': 'off'
}
7. 进阶配置指南
7.1 自定义Webpack配置
通过vue.config.js扩展:
javascript复制module.exports = {
configureWebpack: {
plugins: [
new MyWebpackPlugin()
]
},
chainWebpack: config => {
config.module
.rule('vue')
.use('vue-loader')
.tap(options => {
// 修改选项
return options
})
}
}
7.2 多页面应用配置
javascript复制module.exports = {
pages: {
index: {
entry: 'src/main.js',
template: 'public/index.html',
filename: 'index.html'
},
admin: {
entry: 'src/admin/main.js',
template: 'public/admin.html',
filename: 'admin.html'
}
}
}
8. 项目启动与构建
开发模式:
bash复制yarn serve
# 或
npm run serve
生产构建:
bash复制yarn build
# 或
npm run build
构建分析:
bash复制yarn build --report
9. 测试环境配置
9.1 单元测试
安装Jest:
bash复制yarn add -D jest @vue/test-utils
示例测试:
javascript复制import { mount } from '@vue/test-utils'
import HelloWorld from '@/components/HelloWorld.vue'
test('renders message', () => {
const wrapper = mount(HelloWorld, {
props: {
msg: 'Hello Vue'
}
})
expect(wrapper.text()).toContain('Hello Vue')
})
9.2 E2E测试
使用Cypress:
bash复制yarn add -D cypress
配置脚本:
json复制{
"scripts": {
"test:e2e": "cypress open"
}
}
10. 持续集成配置
GitHub Actions示例:
yaml复制name: CI
on: [push]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: 16
- run: yarn install
- run: yarn test:unit
- run: yarn build
11. 项目部署方案
11.1 静态资源部署
Nginx配置示例:
nginx复制server {
listen 80;
server_name example.com;
root /var/www/my-project/dist;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
}
11.2 Docker化部署
Dockerfile示例:
dockerfile复制FROM node:16 as builder
WORKDIR /app
COPY package.json yarn.lock ./
RUN yarn install
COPY . .
RUN yarn build
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
构建并运行:
bash复制docker build -t my-vue-app .
docker run -p 8080:80 my-vue-app
12. 项目维护与升级
12.1 依赖更新策略
安全更新:
bash复制yarn upgrade-interactive --latest
大版本升级:
bash复制yarn upgrade vue@3
12.2 迁移工具
Vue 2到3迁移助手:
bash复制npm install -g @vue/cli-migrate
vue migrate my-project
13. 性能监控与分析
13.1 Lighthouse审计
bash复制npm install -g lighthouse
lighthouse http://localhost:8080 --view
13.2 Web Vitals监控
安装:
bash复制yarn add web-vitals
使用:
javascript复制import { getCLS, getFID, getLCP } from 'web-vitals'
getCLS(console.log)
getFID(console.log)
getLCP(console.log)
14. 项目文档化
14.1 组件文档生成
使用Storybook:
bash复制npx sb init
yarn add -D @storybook/vue3
配置.storybook/main.js:
javascript复制module.exports = {
stories: ['../src/**/*.stories.@(js|mdx)'],
addons: ['@storybook/addon-essentials']
}
14.2 API文档生成
使用TypeDoc:
bash复制yarn add -D typedoc
配置:
json复制{
"scripts": {
"docs": "typedoc --out docs src"
}
}
15. 移动端适配方案
15.1 视口配置
public/index.html中添加:
html复制<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no">
15.2 响应式设计
使用CSS媒体查询:
css复制@media (max-width: 768px) {
.container {
padding: 0 10px;
}
}
或使用Vue的组合式API:
javascript复制import { ref, onMounted, onUnmounted } from 'vue'
export function useMobile() {
const isMobile = ref(false)
const checkMobile = () => {
isMobile.value = window.innerWidth < 768
}
onMounted(() => {
checkMobile()
window.addEventListener('resize', checkMobile)
})
onUnmounted(() => {
window.removeEventListener('resize', checkMobile)
})
return { isMobile }
}
16. 国际化方案
16.1 Vue I18n安装
bash复制yarn add vue-i18n
16.2 基础配置
src/i18n.js:
javascript复制import { createI18n } from 'vue-i18n'
const messages = {
en: {
greeting: 'Hello!'
},
zh: {
greeting: '你好!'
}
}
const i18n = createI18n({
locale: 'en',
messages
})
export default i18n
16.3 组件中使用
vue复制<template>
<p>{{ $t('greeting') }}</p>
</template>
17. 状态管理进阶
17.1 Pinia安装
bash复制yarn add pinia
17.2 Store定义
src/stores/counter.js:
javascript复制import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0
}),
actions: {
increment() {
this.count++
}
}
})
17.3 组件中使用
vue复制<script setup>
import { useCounterStore } from '@/stores/counter'
const counter = useCounterStore()
</script>
<template>
<button @click="counter.increment">
{{ counter.count }}
</button>
</template>
18. 服务端渲染方案
18.1 Nuxt.js安装
bash复制npx nuxi init my-nuxt-app
cd my-nuxt-app
yarn install
18.2 页面定义
pages/index.vue:
vue复制<template>
<div>
<h1>Welcome to Nuxt!</h1>
</div>
</template>
18.3 启动开发服务器
bash复制yarn dev
19. 微前端集成
19.1 使用qiankun
主应用安装:
bash复制yarn add qiankun
配置:
javascript复制import { registerMicroApps, start } from 'qiankun'
registerMicroApps([
{
name: 'vueApp',
entry: '//localhost:7100',
container: '#subapp-container',
activeRule: '/vue'
}
])
start()
19.2 子应用改造
public-path.js:
javascript复制if (window.__POWERED_BY_QIANKUN__) {
__webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__
}
main.js:
javascript复制import './public-path'
import { createApp } from 'vue'
import App from './App.vue'
let instance = null
function render(props = {}) {
const { container } = props
instance = createApp(App)
instance.mount(container ? container.querySelector('#app') : '#app')
}
if (!window.__POWERED_BY_QIANKUN__) {
render()
}
export async function bootstrap() {
console.log('vue app bootstraped')
}
export async function mount(props) {
render(props)
}
export async function unmount() {
instance.unmount()
instance = null
}
20. 项目脚手架定制
20.1 自定义preset
创建preset.json:
json复制{
"useConfigFiles": true,
"plugins": {
"@vue/cli-plugin-babel": {},
"@vue/cli-plugin-eslint": {
"config": "prettier",
"lintOn": ["save"]
}
},
"router": true,
"vuex": true
}
20.2 使用自定义preset
bash复制vue create --preset ./preset.json my-project
21. 组件库开发
21.1 创建组件库项目
bash复制vue create --preset ./preset.json my-component-lib
21.2 组件开发规范
src/components/Button.vue:
vue复制<template>
<button class="my-button">
<slot></slot>
</button>
</template>
<script>
export default {
name: 'MyButton'
}
</script>
<style scoped>
.my-button {
padding: 8px 16px;
background: #42b983;
color: white;
border: none;
border-radius: 4px;
}
</style>
21.3 打包配置
vue.config.js:
javascript复制const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
css: {
extract: false
},
configureWebpack: {
output: {
libraryExport: 'default'
}
}
})
22. 项目质量保障
22.1 代码覆盖率
Jest配置:
javascript复制module.exports = {
collectCoverage: true,
collectCoverageFrom: [
'src/**/*.{js,vue}',
'!src/main.js'
]
}
22.2 静态分析
使用SonarQube:
bash复制yarn add -D sonarqube-scanner
配置sonar-project.properties:
properties复制sonar.projectKey=my-vue-project
sonar.sources=src
sonar.exclusions=**/node_modules/**
sonar.tests=tests
sonar.test.inclusions=**/*.spec.js
sonar.javascript.lcov.reportPaths=coverage/lcov.info
23. 项目安全加固
23.1 依赖安全检查
bash复制yarn audit
23.2 CSP配置
public/index.html:
html复制<meta http-equiv="Content-Security-Policy"
content="default-src 'self';
script-src 'self' 'unsafe-inline';
style-src 'self' 'unsafe-inline';
img-src 'self' data:;">
23.3 XSS防护
使用DOMPurify:
bash复制yarn add dompurify
使用示例:
javascript复制import DOMPurify from 'dompurify'
const clean = DOMPurify.sanitize(dirtyHTML)
24. 项目性能优化
24.1 懒加载路由
router.js:
javascript复制const routes = [
{
path: '/about',
component: () => import('./views/About.vue')
}
]
24.2 图片优化
使用v-lazy-image:
bash复制yarn add v-lazy-image
使用示例:
vue复制<template>
<v-lazy-image
src="/image.jpg"
src-placeholder="/placeholder.jpg"
/>
</template>
<script>
import VLazyImage from 'v-lazy-image'
export default {
components: {
VLazyImage
}
}
</script>
25. 项目监控与错误追踪
25.1 Sentry集成
安装:
bash复制yarn add @sentry/vue @sentry/tracing
配置:
javascript复制import * as Sentry from '@sentry/vue'
import { Integrations } from '@sentry/tracing'
Sentry.init({
dsn: 'YOUR_DSN',
integrations: [
new Integrations.BrowserTracing({
routingInstrumentation: Sentry.vueRouterInstrumentation(router)
})
],
tracesSampleRate: 1.0
})
25.2 性能监控
使用web-vitals:
bash复制yarn add web-vitals
上报关键指标:
javascript复制import { getCLS, getFID, getLCP } from 'web-vitals'
function sendToAnalytics(metric) {
const body = JSON.stringify(metric)
navigator.sendBeacon('/analytics', body)
}
getCLS(sendToAnalytics)
getFID(sendToAnalytics)
getLCP(sendToAnalytics)
26. 项目文档与协作
26.1 Git工作流
推荐Git Flow:
bash复制git flow init
git flow feature start my-feature
git flow feature finish my-feature
26.2 Commit规范
使用Commitizen:
bash复制yarn add -D commitizen cz-conventional-changelog
配置package.json:
json复制{
"scripts": {
"commit": "git-cz"
},
"config": {
"commitizen": {
"path": "cz-conventional-changelog"
}
}
}
27. 项目模板定制
27.1 创建自定义模板
- 初始化模板项目
- 添加必要文件和配置
- 发布到npm或私有仓库
27.2 使用自定义模板
bash复制vue create --preset username/repo my-project
或直接指定Git仓库:
bash复制vue create --clone my-project git@github.com:username/repo.git
28. 项目升级与迁移
28.1 Vue 2到3迁移
- 安装迁移工具:
bash复制npm install -g @vue/cli-migrate
- 运行迁移:
bash复制vue migrate my-project
28.2 依赖升级策略
- 检查过时依赖:
bash复制yarn outdated
- 交互式升级:
bash复制yarn upgrade-interactive --latest
29. 项目架构设计
29.1 分层架构
推荐结构:
code复制src/
├── core/ # 核心业务逻辑
├── services/ # API服务层
├── stores/ # 状态管理
├── composables/ # 组合式函数
├── utils/ # 工具函数
├── assets/ # 静态资源
├── components/ # 通用组件
├── views/ # 页面组件
└── router/ # 路由配置
29.2 模块化设计
使用动态导入:
javascript复制const module = await import('./module.js')
30. 项目发布与部署
30.1 CI/CD配置
GitHub Actions示例:
yaml复制name: CI/CD
on:
push:
branches: [ main ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: 16
- run: yarn install
- run: yarn build
- run: yarn test
- uses: actions/upload-artifact@v3
with:
name: dist
path: dist
deploy:
needs: build
runs-on: ubuntu-latest
steps:
- uses: actions/download-artifact@v3
with:
name: dist
- uses: appleboy/scp-action@master
with:
host: ${{ secrets.SSH_HOST }}
username: ${{ secrets.SSH_USER }}
key: ${{ secrets.SSH_KEY }}
source: "dist/*"
target: "/var/www/html"
30.2 自动化部署脚本
deploy.sh:
bash复制#!/bin/bash
# 构建
yarn build
# 同步到服务器
rsync -avz --delete dist/ user@server:/var/www/html
# 重启服务
ssh user@server "sudo systemctl restart nginx"
31. 项目维护与监控
31.1 错误监控
使用Sentry配置错误边界:
vue复制<template>
<SentryErrorBoundary>
<!-- 应用内容 -->
</SentryErrorBoundary>
</template>
<script>
import * as Sentry from '@sentry/vue'
export default {
errorCaptured(err, vm, info) {
Sentry.captureException(err)
return false
}
}
</script>
31.2 性能监控
使用Web Vitals API:
javascript复制import { getCLS, getFID, getLCP } from 'web-vitals'
function sendToAnalytics(metric) {
const body = JSON.stringify(metric)
navigator.sendBeacon('/analytics', body)
}
getCLS(sendToAnalytics)
getFID(sendToAnalytics)
getLCP(sendToAnalytics)
32. 项目文档自动化
32.1 组件文档
使用Storybook配置:
.storybook/main.js:
javascript复制module.exports = {
stories: ['../src/**/*.stories.@(js|mdx)'],
addons: ['@storybook/addon-essentials']
}
组件故事示例:
javascript复制import MyButton from './MyButton.vue'
export default {
title: 'Components/MyButton',
component: MyButton
}
const Template = (args) => ({
components: { MyButton },
setup() {
return { args }
},
template: '<MyButton v-bind="args">Button</MyButton>'
})
export const Primary = Template.bind({})
Primary.args = {
primary: true
}
32.2 API文档
使用TypeDoc配置:
typedoc.json:
json复制{
"entryPoints": ["src/main.ts"],
"out": "docs",
"exclude": ["**/*.spec.ts", "**/__tests__/**"]
}
33. 项目测试策略
33.1 单元测试覆盖率
Jest配置示例:
jest.config.js:
javascript复制module.exports = {
collectCoverage: true,
collectCoverageFrom: [
'src/**/*.{js,vue}',
'!src/main.js'
],
coverageThreshold: {
global: {
branches: 80,
functions: 80,
lines: 80,
statements: 80
}
}
}
33.2 E2E测试覆盖率
Cypress配置示例:
cypress.json:
json复制{
"video": false,
"baseUrl": "http://localhost:8080"
}
测试示例:
javascript复制describe('My Test Suite', () => {
it('visits the app', () => {
cy.visit('/')
cy.contains('h1', 'Welcome to Your Vue.js App')
})
})
34. 项目安全审计
34.1 依赖安全检查
使用npm audit:
bash复制npm audit
或使用yarn:
bash复制yarn audit
34.2 代码安全扫描
使用ESLint安全插件:
bash复制yarn add -D eslint-plugin-security
配置.eslintrc.js:
javascript复制module.exports = {
plugins: ['security'],
extends: ['plugin:security/recommended']
}
35. 项目性能审计
35.1 Lighthouse审计
运行本地审计:
bash复制npm install -g lighthouse
lighthouse http://localhost:8080 --view
35.2 Webpack Bundle分析
安装分析工具:
bash复制yarn add -D webpack-bundle-analyzer
配置vue.config.js:
javascript复制const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
module.exports = {
configureWebpack: {
plugins: [
new BundleAnalyzerPlugin()
]
}
}
36. 项目持续改进
36.1 代码质量监控
使用SonarQube配置:
sonar-project.properties:
properties复制sonar.projectKey=my-vue-project
sonar.sources=src
sonar.exclusions=**/node_modules/**
sonar.tests=tests
sonar.test.inclusions=**/*.spec.js
sonar.javascript.lcov.reportPaths=coverage/lcov.info
36.2 性能基准测试
使用Benchmark.js:
bash复制yarn add benchmark
测试示例:
javascript复制import Benchmark from 'benchmark'
import { computed, ref } from 'vue'
const suite = new Benchmark.Suite()
suite
.add('Computed', () => {
const count = ref(0)
const double = computed(() => count.value * 2)
double.value
})
.on('cycle', event => {
console.log(String(event.target))
})
.run()
37. 项目扩展方案
37.1 微前端集成
使用qiankun主应用配置:
javascript复制import { registerMicroApps, start } from 'qiankun'
registerMicroApps([
{
name: 'vueApp',
entry: '//localhost:7100',
container: '#subapp-container',
activeRule: '/vue'
}
])
start()
37.2 服务端渲染扩展
使用Nuxt.js创建SSR应用:
bash复制npx nuxi init my-ssr-app
cd my-ssr-app
yarn install
38. 项目架构演进
38.1 模块化架构
按功能拆分模块:
code复制src/
├── modules/
│ ├── auth/
│ │ ├── components/
│ │ ├── services/
│ │ ├── stores/
│ │ └── views/
│ └── dashboard/
│ ├── components/
│ ├── services/
│ ├── stores/
│ └── views/
38.2 微前端架构
基座应用配置:
javascript复制import { registerMicroApps, start } from 'qiankun'
registerMicroApps([
{
name: 'moduleA',
entry: '//localhost:7101',
container: '#module-container',
activeRule: '/module-a'
}
])
start()
39. 项目文档体系
39.1 技术文档
使用VitePress:
bash复制yarn add -D vitepress
配置docs/.vitepress/config.js:
javascript复制module.exports = {
title: 'My Project',
description: 'Project Documentation',
themeConfig: {
nav: [
{ text: 'Guide', link: '/guide' }
]
}
}
39.2 API文档
使用TypeDoc:
bash复制yarn add -D typedoc
配置typedoc.json:
json复制{
"entryPoints": ["src/main.ts"],
"out": "docs/api"
}
40. 项目知识管理
40.1 内部Wiki
使用GitBook配置:
book.json:
json复制{
"plugins": ["theme-default"],
"variables": {
"title": "My Project Wiki"
}
}
40.2 代码审查规范
GitHub PR模板:
.github/PULL_REQUEST_TEMPLATE.md:
markdown复制## 变更描述
## 相关Issue
## 测试说明
## 附加说明
41. 项目团队协作
41.1 Git工作流
推荐Git Flow:
bash复制git flow init
git flow feature start my-feature
git flow feature finish my-feature
41.2 Code Review规范
.eslintrc.js:
javascript复制module.exports = {
rules: {
'complexity': ['warn', 10],
'max-lines-per-function': ['warn', 50]
}
}
42. 项目质量门禁
42.1 提交前检查
使用Husky:
bash复制yarn add -D husky lint-staged
配置package.json:
json复制{
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"*.{js,vue}": [
"eslint --fix",
"prettier --write"
]
}
}
42.2 CI质量门禁
GitHub Actions示例:
yaml复制jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
- run: yarn install
- run: yarn test
- run: yarn build
- run: yarn lint
43. 项目监控告警
43.1 错误监控
Sentry配置:
javascript复制import * as Sentry from '@sentry/vue'
import { Integrations } from '@sentry/tracing'
Sentry.init({
dsn: 'YOUR_DSN',
integrations: [
new Integrations.BrowserTracing({
routingInstrumentation: Sentry.vueRouterInstrumentation(router)
})
],
tracesSampleRate: 1.0
})
43.2 性能监控
Web Vitals上报:
javascript复制import { getCLS, getFID, getLCP } from 'web-vitals'
function sendToAnalytics(metric) {
const body = JSON.stringify(metric)
navigator.sendBeacon('/analytics', body)
}
getCLS(sendToAnalytics)
getFID(sendToAnalytics)
getLCP(sendToAnalytics)
44. 项目自动化运维
44.1 自动化部署
GitHub Actions配置:
yaml复制deploy:
needs: build
runs-on: ubuntu-latest
steps:
- uses: actions/download-artifact@v3
with:
name: dist
- uses: appleboy/scp-action@master
with:
host: ${{ secrets.SSH_HOST }}
username: ${{ secrets.SSH_USER }}
key: ${{ secrets.SSH_KEY }}
source: "dist/*"
target: "/var/www/html"
- uses: appleboy/ssh-action@master
with:
host: ${{ secrets.SSH_HOST }}
username: ${{ secrets.SSH_USER }}
key: ${{ secrets.SSH_KEY }}
script: "sudo systemctl restart nginx"
44.2 监控脚本
monitor.sh:
bash复制#!/bin/bash
# 检查进程
if ! pgrep -x "nginx" > /dev/null
then
echo "Nginx is down!" | mail -s "Alert" admin@example.com
fi
# 检查磁盘
DISK_USAGE=$(df -h / | awk 'NR==2 {print $5}' | cut -d'%' -f1)
if [ "$DISK_USAGE" -gt 90 ]
then
echo "Disk is almost full!" | mail -s "Alert" admin@example.com
fi
45. 项目备份策略
45.1 数据库备份
backup-db.sh:
bash复制#!/bin/bash
DATE=$(date +%Y%m%d)
BACKUP_DIR="/backups/db"
DB_NAME="myapp"
mysqldump -u root -p$DB_PASSWORD $DB_NAME > $BACKUP_DIR/$DB_NAME-$DATE.sql
find $BACKUP_DIR -type f -mtime +30 -delete
45.2 代码备份
使用Git镜像:
bash复制git clone --mirror git@github.com:user/repo.git
cd repo.git
git remote update
46. 项目灾难恢复
46.1 恢复流程
- 从备份恢复数据库
- 重新部署代码
- 验证服务状态
46.2 恢复测试
定期执行:
bash复制./restore-test.sh
restore-test.sh:
bash复制#!/bin/bash
# 测试数据库恢复
mysql -u root -p$DB_PASSWORD test_db < latest-backup.sql
# 验证数据
if mysql -u root -p$DB_PASSWORD -e "USE test_db; SELECT COUNT(*) FROM users;" | grep -q "0"
then
echo "Restore failed"
exit 1
fi
47. 项目成本优化
47.1 资源监控
使用Prometheus配置:
prometheus.yml:
yaml复制scrape_configs:
- job_name: 'node'
static_configs:
- targets: ['localhost:9100']
47.2 自动伸缩
Kubernetes HPA配置:
hpa.yaml:
yaml复制apiVersion: autoscaling/v2beta2
kind: HorizontalPodAutoscaler
metadata:
name: myapp
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: myapp
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 50
48. 项目安全加固
48.1 依赖更新
使用Dependabot:
.github/dependabot.yml:
yaml复制version: 2
updates:
- package-ecosystem: "npm"
directory: "/"
schedule:
interval: "weekly"
48.2 安全扫描
使用Trivy:
bash复制docker run --rm -v /:/host aquasec/trivy fs --
