preface
I’ve worked with many blogging platforms: WordPress, Jekyll, Hexo, Typecho and Vuepress. Some of them are static and some require server maintenance. After all the bells and whistles, I’ve come to believe that blogging is about thinking and recording, not decorating. So summarize some experience can let everyone quickly set up a blog, and do not worry about the subsequent maintenance. This article is not a nannytutorial, the target group is a certain work experience developers need out-of-the-box blog publishing solutions, some small problems such as Node installation, Github access, domain name purchase record, Vim exit need to solve themselves, then let’s go!
Making Actions deployment
VuePress use
The front-end library vue.js was previously driven by Hexo, but the Vue authors struggled with page loading performance and SEO and created VuePress to better unleash Vue, which is what we’re going to create next.
After node. js is installed, you can run it on the cli. When YARN Init is performed, you do not need to type anything and press Enter.
mkdir vuepress-blog && cd vuepress-blog
yarn init
yarn add -D vuepress
mkdir docs && echo '# Hello VuePress' > docs/README.md
Copy the code
Package. json can be changed to
{" name ":" vuepress - blog ", "version" : "1.0.0", "main" : "index. Js", "license" : "MIT", "devDependencies" : {" vuepress ": "^1.8.2"}, "scripts": {"dev": "vuepress dev docs", "build": "vuepress build docs"}Copy the code
runyarn dev
After open thehttp://localhost:8080/
It’s just a really crude “Hello VuePress,” but yeahdocs/.vuepress/config.js
Slightly modify and add the corresponding directory files can be online to meet, the meaning of each field referenceVuePress document, can also be based onMy blogReplace it with your own Markdown document and file path.
- Markdown: Configures the rendering of markdown, such as line numbers and plug-ins for code blocks, title anchors, and outer chains
- Title: Site title
- Description: Website description
- ThemeConfig: dependent topic,
nav
Configure the upper-right navigation,sidebar
The left navigation corresponds to a file or folder under the Docs folder, remembersidebar
The last entry in the array/ :
An empty array of strings cannot be discarded because this represents a home page readme.md. - Base: especially important if accessed directly
https://[username].github. IO
By default, we don’t have to, so our example base is going to be"/vuepress-publish/"
, can be accessed after uploadinghttps://[user name].github. IO /vuepress-publish
// config.js module.exports = { base: "/vuepress-publish/", title: 'the grizzlies の blog'} / / https://github.com/huixiongyu/blog docs /. Vuepress/config. Js configuration module. Exports = {markdown: {lineNumbers: }, title: 'full stack Coder', head: [['link', {rel: 'icon', href: '/ flower. Ico}]], themeConfig: {nav: [{the text: "blog" link: "/ blog/"}, {text:' read ', the link:"/book/"}, {text: 'making' link: 'https://github.com/huixiongyu/blog'}], sidebar: {'/blog / : [', {title: 'life', collapsable: true, children: [ '/blog/Life/my-action-list', '/blog/Life/train-habit', '/blog/Life/about-PG-entrance-exam', '/blog/Life/graduation-thesis' ] }, ... ... ... ] , '/ book / : [' and' plan - and - record, {title: 'front end related, collapsable: true, children:[ '/book/HTML&CSS/02-css-secrets' ] }, ... ... ... ] , '/': [ '' ] }, sidebarDepth: 2, displayAllHeaders: true, nextLinks: true, prevLinks: true, lastUpdated: 'Update time ', docsDir: 'docs', editLinks: true, editLinkText:' Help me improve this content 🙏'}}Copy the code
Build making Page
Add a name on a lot of private warehouse vuepress – blog, and then create a public warehouse vuepress – public, the idea here is blog source file (md files and config. Js, etc.) are private protection articles will not be handling (I set to open for the convenience of reference), After submitting the code, GitHub will help us build static files rendered as HTML and push them to vuepress-public’s GH-Pages branch, which users can access via https://[username].github. IO /vuepress-public. Create a.yML file by clicking “Set Up a Workflow Yourself” on the Actions bar of the repository and naming it “Main” or “CI”. After clicking save, it will appear in the code root directory. Github/Workflow folder. Here, it is recommended not to save, there is a follow-up step, use the right click and choose “Open link in a new TAB” to operate our next step: apply for Token and set Secret.
The code for Actions is as follows:
name
Define the workflow name;on
Record the conditions that trigger this is the master branchpush
When executing;- Below JOBS is the collection of tasks
build
Is a job, you can also inbuild
Create a new jobs on the same level as the “jobs”, and name it with the meaning of the execution step. runs-on
Ubuntu, Windows, and macOS are available.steps
Is the execution step of a single job. Here, it is to obtain the code branch and run the Vuepress deployment.uses
Select an official or third-party action stepactions/
Informal (user-initiated) is used[user name]/[warehouse name]
To labeling.env
The dependent action needs to pass in the environment variable, note our use${{ secrets.XXX }}
To introduce information that is not easy to expose, how to configure is our next step.
name: CI on: push: branches: [ master ] jobs: build: runs-on: ubuntu-latest steps: -name: Checkout uses: actions/checkout@master - name: vuepress-deploy uses: jenkey2011/vuepress-deploy@master env: ACCESS_TOKEN: ${{ secrets.TOKEN }} TARGET_REPO: huixiongyu/vuepress-publish TARGET_BRANCH: gh-pages BUILD_SCRIPT: yarn && yarn build BUILD_DIR: docs/.vuepress/dist/ CNAME: ${{ secrets.CNAME }}Copy the code
The Action of the introduction ofTOKEN
From GitHub. Select the profile picture in the upper right corner of the warehouse from the drop-down listSettings
Find after jumpDeveloper settings
In thePersonal access Tokens
Create, check repo, if long-term use remember to create again. The token will be displayed immediately after submission. Copy the token in time and it will not appear again.Copy and return to the repositoryvuepress-blog
You can create a password book by selecting Secrets under Settings.Name
Are the Actions${{ secrets.XXX }}
theXXX
And theValue
That’s what you’re actually passing in. Here we areName
Fill in theTOKEN
thenValue
Paste the authorization string you just applied for.CNAME
Can let us use the value of the domain name directly access[Username].github. IO
If you have purchased a domain name in Ali Cloud, Namecheap, Tencent Cloud, etc., you can do it in the domain name consoleGitHub CNAME configuration. If you don’t have a personal domain name, remove the CNAME line from the Actions code.After setting all the required Secrets can be saved.yml
Click the Actions TAB to see the GitHub VIRTUAL machine Actions log. If the Actions are successful, there will be a green check box. Otherwise, ❌ will appear. And the code repositoryvuepress-publish
There will be an update to the GH-Pages branch. Because I set CNAME,https://www.hackslog.com/vuepress-publish/
(I later changed the domain name to blog.hackslog.com) to access the built web page, which was locally logged as beforehttp://localhost:8080/
If CNAME is not set and my GitHub user name is Huixiongyu, the access link ishttps://huixiongyu.github.io/vuepress-publish/
.
Deployed to the OSS
OSS is the object storage service of Ali Cloud, that is, file storage. After uploading files, users can get the accessible link of the public network. With CDN acceleration, users can quickly access data nodes in close proximity. Alibaba Cloud, Qiuniuyun, Huawei cloud and other object storage products use the same way, the cost is only a few yuan a year, can be trusted to use.You can create buckets in the OSS administrative console at will. For individual websites, you can use one Bucket for each site to prevent resource clutter. If the HTTP header or HTTP header is not configured in the file details after a file is uploaded using the consoleBind custom domain namesIn addition, if you want to use HTTPS access, it is also configured in the console -> Transfer Management. You can directly check the prompt document and apply for a free SSL certificate as long as you are careful. After you have applied for the certificate in the SSL console, click deploy on the far right. The certificate you just applied for seems to take half or an hour to take effect. You can do something else.
Go back tovuepress-blog
Warehouse Actions code, need to add a job will build out the static web page directly uploaded OSS, so.github/workflows/main.yml
The complete code is as follows:
name: CI on: push: branches: [ master ] jobs: build: runs-on: ubuntu-latest steps: -name: Checkout uses: actions/checkout@master - name: vuepress-deploy uses: jenkey2011/vuepress-deploy@master env: ACCESS_TOKEN: ${{ secrets.TOKEN }} TARGET_REPO: huixiongyu/vuepress-publish TARGET_BRANCH: gh-pages BUILD_SCRIPT: yarn && yarn build BUILD_DIR: docs/.vuepress/dist/ CNAME: ${{ secrets.CNAME }} build-to-OSS: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@master - name: Setup Node.js uses: actions/setup-node@v1 with: node-version: '14.x' - name: Build Web run: | node changeOssPath.js yarn add -D vuepress yarn install yarn build echo '${{ secrets.OSS_CNAME }}' > docs/.vuepress/dist/CNAME mv docs/.vuepress/dist ./ - name: Upload to OSS env: OSS_REGION: ${{ secrets.OSS_REGION }} OSS_BUCKET: ${{ secrets.OSS_BUCKET }} OSS_KEY: ${{ secrets.OSS_KEY }} OSS_SECRET: ${{ secrets.OSS_SECRET }} OSS_URL: ${{ secrets.OSS_URL }} run: | ls pwd node ossSync.js - name: Upload to Could Computer uses: appleboy/scp-action@master with: host: ${{ secrets.IP_ADDRESS }} username: ${{ secrets.SERVER_USER }} port: "${{ secrets.SERVER_PORT }}" key: ${{ secrets.SERVER_PRIVATE_KEY }} source: "dist/**" target: "${{ secrets.TARGET_PATH }}"Copy the code
Don’t save the code, we also need to add some private information in Settings->Secret, which can be obtained from the console that created the Bucket and the “AccessKey Management” displayed on the upper right. AccessKey should not be written directly into the code. Since I had full access to all buckets, I also wrote some scripts, such as osssync.js, to facilitate the upload. Upload to Could Computer. If you don’t need it, you can delete it
- TOKEN: GitHub warehouse management authorization string
- CNAME: GitHub Page custom domain name
- OSS_CNAME: user-defined domain name for OSS access, the same as that bound to Bucket
- OSS_REGION: indicates the region to which the Bucket belongs, for example, OSs-CN-Hangzhou in Guangzhou
- OSS_REGION: user-defined Bucket name, for example, huixiong-blog
- OSS_KEY: the AccessKey ID
- OSS_SECRET: key corresponding to the AccessKey Id
- OSS_URL: custom domain name, write default if not, such as huixiong-blog.oss-cn-guangzhou.aliyuncs.com
- IP_ADDRESS: indicates the IP address
- SERVER_USER: indicates the login user name
- SERVER_PORT: transmission port. The default value is 22
- SERVER_PRIVATE_KEY: symmetric private key. The value is a character string
BEGIN RSA PRIVATE KEY
- TARGET_PATH: The directory to transfer to the server
After the Secret and code are saved, soon the Actions are finished, and the OSS console sees the files updated, and the web page is accessible.
Further Actions
Github Actions is a continuous integration process. Operational deployment involves many steps such as pulling code, testing, building artifacts, logging in to remote servers, running commands on remote servers, etc. Github refers to these as Actions. GitHub discovered that these tasks could be reused and combined at will, so they defined rules such as unifying the meaning of constants, limiting the output of private information, and unifying the format of actions files, creating an official marketplace for free use. The process of using Actions becomes a process of using someone else’s script and writing your own. The work environment is the root directory of the code. What commands are required to manually push vuepress-blog to another repository branch? You would write something like this:
- Set up the online node.js version and install dependencies
- The dist folder will appear under the docs/.vuepress directory
- Go to the dist folder and write down the CNAME
- Initialize Git and push the folder into a branch
yarn install
yarn build
cd docs/.vuepress/dist
ls
echo 'hackslog.com' > CNAME
git init
git config --global user.email "[email protected]"
git config --global user.name "huixiongyu"
git add .
git commit -m "deploy"
git push --force "https://${{ secrets.TOKEN }}@github.com/huixiongyu/vuepress-publish.git" master:gh-pages
Copy the code
At the beginning, I also wrote some scripts in Actions, but I tried to build dist for 20 or 30 times, but I couldn’t get dist to vuepress-publish anyway. Later, I searched the plugin market, and just configured the variables of copy. If you need multiple nodes, you can easily deploy blogs to Github, code cloud, Coding, Gitlab…
- name: vuepress-deploy
uses: jenkey2011/vuepress-deploy@master
env:
ACCESS_TOKEN: ${{ secrets.TOKEN }}
TARGET_REPO: huixiongyu/vuepress-publish
TARGET_BRANCH: gh-pages
BUILD_SCRIPT: yarn && yarn build
BUILD_DIR: docs/.vuepress/dist/
CNAME: ${{ secrets.CNAME }}
Copy the code
I couldn’t seem to find a suitable script for uploading to OSS, so I started writing my own. The node.js SDK provided by Lialiyun is used to get the keys passed by actions through process.env and initialize them. GetLocalFileList iterates the names of all files to be uploaded to OSS, and then iterates the array of files using putOneFile and posts them one by one. If OSS already has a file with the same name, it will be overwritten. Error: EISDIR: EISDIR: Illegal operation on a directory, read: fs.readdirsync ‘ ‘fs.readfilesync’
const fs = require('fs') const OSS = require('ali-oss') const { OSS_REGION, OSS_BUCKET, OSS_KEY, OSS_SECRET, OSS_URL, } = process.env; Const client = new OSS({region: OSS_REGION, // Create bucket selected region bucket: OSS_BUCKET, // Bucket name accessKeyId: OSS_KEY, // accessKeyId accessKeySecret: OSS_SECRET, // accessKeySecret }); function getLocalFileList(basePath) { console.log(`current path is:${basePath}`) const fileNamelist = fs.readdirSync(basePath) console.log(fileNamelist) let result = [] fileNamelist.forEach(name => { const file = basePath + name const statsObj = fs.statSync(file); if (statsObj.isFile()) { result.push(file) } else { result = result.concat(getLocalFileList(file + '/')); } }) return result; } async function putOneFile(fileName, dir) { try { const result = await client.put(fileName, dir); console.log(OSS_URL + result.name); } catch (e) { console.log(e); } } async function main() { console.log('ossSync working... ') const fileList = getLocalFileList(__dirname + '/dist/') console.log(fileList) for(const file of fileList) { const tempList = file.split('/dist/') const fileName = tempList[1] await putOneFile(fileName, file) } console.log('ossSync completed! ') } main()Copy the code
There is also a script to fix bugs when deploying to different environments. Config.js did not write base: “/vuepress-publish/”, which would invalidate CSS styles in one environment. If you want to deploy directly in [username].github. IO repository, you need to understand the meaning of base, you can delete the base in config.js, and deploy in the domain root directory whether OSS or cloud server can keep the node changeOssPath.
// changeOssPath.js
const fs = require('fs')
let content = fs.readFileSync('docs/.vuepress/config.js', 'utf8')
content = content.replace(/base:\s["']{1}[\/A-Za-z0-9_-]*["']{1},/g, '')
console.log(content)
fs.writeFileSync('docs/.vuepress/config.js', content, { flag: 'w' })
Copy the code
You might also question the security of Actions, but I’ve implemented my own configuration of Secret in the console, which is replaced by* * * *
In addition, the official market is for security-verified scripts, and other repositories are open source. The permissions of Actions run in their own space are managed by GitHub apis, and they are not conditional on collecting any private information. So the first responsibility for security is the developers themselves, and try to read the source code and share your own. Github Actions is a very interesting feature that allows people to use their talents to tap into the resources of the server, such as crawlers, scheduled tasks, etc. Auto-green simply makes use of the CronTab effect of Action to push the code at a regular time and let yourself clock in full time.
name: ci on: push: branches: - master schedule: - cron: "0 */4 * * *" jobs: autogreen: runs-on: ubuntu-latest steps: - name: Clone repository uses: actions/checkout@v2 - name: Auto green run: | git config --local user.email "[email protected]" git config --local user.name "huixiongyu" git remote set-url origin https://${{ github.actor }}:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }} git pull --rebase git commit --allow-empty -m "Stay hungry, stay foolish!" git pushCopy the code
Deploy to the cloud server
Transferring the Dist folder to your personal cloud server is done using Nginx reverse proxy. Here’s how to connect, and the next section covers Nginx. The IP address, user name, port number, and password are used to connect to the server. However, you are advised to use the password because the password permission is too highSSH key pair, enter the ECS console can find the corresponding entry, generated.cer
Like Github Token, files are saved only once.
- name: Upload to Could Computer
uses: appleboy/scp-action@master
with:
host: ${{ secrets.IP_ADDRESS }}
username: ${{ secrets.SERVER_USER }}
port: "${{ secrets.SERVER_PORT }}"
key: ${{ secrets.SERVER_PRIVATE_KEY }}
source: "dist/**"
target: "${{ secrets.TARGET_PATH }}"
Copy the code
The above is SCP file upload, if you still want to have more operation commands in your own cloud server, you can also usessh-action.
Ali Cloud effect deployment
The use of Hexo
If you want to use a waterfall stream effect blog, try Hexo. The platform has a large user base, rich themes and can be configured with a variety of things, such as Next and Fluid
npm install -g hexo-cli
hexo init hexo-blog
cd hexo-blog
npm install
Copy the code
Yml is the configuration information of the website, such as site name, theme, folder name. Themes are stored in the clone folder. Source contains drafts and published articles.
. ├ ─ ─ _config. Yml ├ ─ ─ package. The json ├ ─ ─ scaffolds ├ ─ ─ source | ├ ─ ─ _drafts | └ ─ ─ _posts └ ─ ─ themesCopy the code
The command line:
Hexo New "Plans for December"
Create a post titled “December plans” in the _posts folderhexo server
: Preview the effect of the site,http://localhost:4000
Open the web pagehexo generate
Static files are generated in the public folder under the root directory
Cloud effect OSS deployment
Ali Cloud effect is an excellent team collaboration platform, free available code storage of 5GB, schedule and kanban tracking tasks, block level rich text editor like Confluence and Notion, Jenkins like but easier to use pipeline free build, finished product warehouse, authority segmentation and isolation management system. Note that the same computer can actually manage multiple Git accounts, the method is in usessh-keygen
Pay attention to input~/.ssh/
The file name of the directory, and then use it separatelyssh-add
Add these files for examplessh-add ~/.ssh/id_rsa_aliyun
Although I can identify different accounts, I need to config their respective username and email after each creation or clone. Later, I adopted global cloud effect only, and Github used client management.Hexo uploads code to the repository before deploying, and is managed like GitHub:Option 2:Click on the small box at the top left of the console, as shown in the red box in the first image of cloud Effect click on Pipeline and then create pipeline. There are many templates to choose from, here select OSS.When showing the screen below, go ahead and build and upload. Codeup is a cloud-enabled repository, and if your code is on GitHub, you can also apply for authorization via Settings->Security. Because ali cloud internal resources integration, code warehouse can be found quickly.After the code enters the virtual cloud host, the command to run is:
cnpm install
npm install hexo-cli -g
hexo g
Copy the code
Click on the service license to select the independent bucket where the blog is located. The Bucket Folder should be empty to upload to the root directory. Images are just tests. If you click save and run, public will be automatically uploaded to the root directory. In this case, you can access the web page by using the custom domain name of the Bucket binding without writing the deployment script.
The cloud effect is deployed on the server
When deploying to ECS and its own host, click the corresponding template to create pipeline, and the build upload command is the same as before. The difference is that the files in the public folder will be packaged and sent to the directory set by the server. If you have multiple pipelines executing to the same host, you need to change the name to different. Ali cloud buy ECS can be quickly selected, if it is other cloud host choiceCreating a Host Group
You will be prompted to run a command to install the agent on the host.My deployment script is as follows: Delete the existing files and decompress the uploaded files to the target folder. If no folder exists in the directory, you need to create it in advance; otherwise, an error message will be reported.
rm -rf /usr/local/nginx/hexo/*
tar zxvf /home/admin/app/hexo-package.tgz -C /usr/local/nginx/hexo
Copy the code
After saving and running, the linked server can view the file updates, and now it is time to configure Nginx.
Nginx
Install nginx, if the configuration is not available, you can refer to other resources, nginx configuration can be smooth.
Wget http://nginx.org/download/nginx-1.18.0.tar.gz tar - XZF nginx - 1.18.0. Tar. Gz / / cmake rely on # $sudo apt - get the update $sudo apt-get install GCC # Nginx $sudo apt-get install make # $sudo apt-get install libz-dev $ sudo apt-get install libpcre3-dev $ sudo apt-get install libssl-devCopy the code
The nginx directory starts nginx at: /usr/local/nginx
$CD /usr/local/nginx/sbin $./nginx $curl http://localhost #Copy the code
Common nginx commands include:
/nginx -t # check whether the nginx.conf configuration is normal./nginx -s reload # hot loading./nginx -s stop # stop./nginx -s Reopen # Reopen the logCopy the code
My nginx configuration files in/usr/local/nginx/conf/nginx. Under the conf, using Vim editor Vim nginx. Conf, Press ESC, enter :wq, and then go to sbin. Hot clip on nginx./nginx -s reload
server { listen 80; server_name hexo.hackslog.com; location / { root hexo; index index.html; }}Copy the code
Access successful!There is a lot of room for further optimization of Hexo. I had a lot of fun with PV/UV statistics, article top, Kanban girl, Canvas background, mouse click effect, comment reply, etc. I still need to write articles after the update.
Cloudbase static web hosting
Tencent cloud Cloudbase interesting this product, their design concept is to help enterprise quickly on cloud, functions such as login, log on daily development code, database query, file storage and process them through the API to provide developers the ability to call the clouds, and then for general platform they have CMS provides unified management. This development mode can realize rapid development and save the trouble of operation and maintenance, but the disadvantage is that the platform depends on serious migration difficulties. Static web hosting they provide templates, but our purpose is to use our own code to upload to their storage space, the space under the page CNAME configure a visitor’s link on the line.
Sudo NPM i-g@cloudbase /cli Tcb-v # hexo-blog # hexo-blog # cloudbase login # hexo-blog # hexo-blog # cloudbase login # hexo-blog public -e envIdCopy the code
Hexo-blog is the same warehouse we used before. EnvId gave you the ID after Tencent Cloud was created. Please confirm that it has been used before deploymenthexo g
To generate a static file for the blog.Soon, all files under public will be uploaded to space, not much different from the files pushed to the object store.Through the domain name, we can directly access the blog just published. If you need a beautiful access link, you can directly configure the CNAME in the console. In addition, the access to these Spaces is charged by volume, which is about the same as the price of object storage, a few dollars a year.
Writing this article took a lot of time to verify, and although it seems to be true, the former Travis CI has been replaced by GitHub Action to keep up with The Times. Creation is not easy, your praise is my biggest encouragement!