How to use Docker to build a development environment (Windows and Mac)

How to use Docker to build a development environment (Windows and Mac)

We all encounter this problem during development: after developing a function locally, when it is deployed to the server, or when others pull it to the local server to continue development, the function may become unusable.

Most of these exceptions are caused by dependency differences due to different systems. Therefore, in order to solve this problem, there is a need to build a unified development environment based on Docker.

For basic knowledge about docker, please refer to the docker tutorial.

1. Benefits of using Docker

Easy to deploy

It usually takes a long time for us to build the environment. When it comes to teamwork, every time a new person comes in, avoidable time is wasted. Moreover, various problems often arise when building the environment, causing the project code to run abnormally. If Docker is used, only the first person needs to write the development container, and others only need to pull it down to complete the construction of the project environment, which can effectively avoid meaningless waste of time.

Isolation

We often deploy multiple project environments on one computer. If they are installed directly, they may interfere with each other. For example, one project requires Node.js 14, while another requires Node.js 12. If they are deployed directly on the local machine, they cannot coexist. If Docker is used, this problem can be avoided. Docker also ensures that each application uses only the resources allocated to it (including CPU, memory, and disk space). A particular software will not use all of your available resources, which would otherwise cause performance degradation or even make other applications stop working completely.

2. Install Docker

1) Install Docker on Linux

Taking Arch Linux as an example, other distributions are similar, except that they use different package management tools.

# Set up a domestic mirror station, which is used to speed up the domestic operation. It is optional. $ sudo pacman-mirrors -i -c China -m rank

# Install Docker using Pacman
$ sudo pacman -S docker

# Create a docker user group. By default, the docker command uses a Unix socket to communicate with the Docker engine. Only the root user and users in the docker group can access the Unix socket of the Docker engine. For security reasons, the root user is generally not used directly on Linux systems. Therefore, a better approach is to add users who need to use docker to the docker user group.
$ sudo groupadd docker

# Add the current user to the docker group. The changes will take effect after you log out of the current terminal and log in again. $ sudo usermod -aG docker $USER

# Test whether the installation is successful $ docker run --rm hello-world

2) Windows 10

It is relatively simple to install Docker on Windows 10. There are several ways to do this:

Manual download and installation:

Download Docker Desktop for Windows. Since the download from the official website is slow, you can click this link if you need to download locally

After downloading, double-click Docker Desktop Installer.exe to start the installation.

Install using winget:

$ winget install Docker.DockerDesktop

Run Docker:

Type Docker in the Windows search bar and click Docker Desktop to start.

After Docker is started, a whale icon will appear in the Windows taskbar.

Wait for a while. When the whale icon becomes still, it means Docker is started successfully. You can then open PowerShell/CMD/Windows Terminal to use Docker.

3) macOS

Install using Homebrew:

Homebrew's Cask already supports Docker Desktop for Mac, so it is easy to install using Homebrew Cask:

$ brew install --cask docker

Manual download and installation:

If you need to download manually, click Download Docker Desktop for Mac. Since the download from the official website is slow, you can click this link if you need to download locally

Please pay attention to download the software corresponding to the chip type. The versions corresponding to M1 and Intel chips are not universal.

Like other macOS software, the installation is very simple. Double-click the downloaded .dmg file, and then drag the whale icon called Moby to the Application folder (you need to enter the user password during this process).

Run Docker:

Find the Docker icon from Applications and click Run.

After running, you will see a whale icon in the upper right corner of the menu bar, which indicates the running status of Docker.

After the installation is complete and started, we can check the installed Docker version through the command in the terminal.

$ docker --version

3. Docker source change

The default source of docker is foreign, and the speed of domestic access is relatively slow, so you can switch to a domestic source to increase the speed of pulling images.

1) Linux source change

It is relatively simple under Linux. Just create a deamon.json file and write down the configuration:

$ vi /etc/docker/deamon.json

# Input mirror source {
  # It is also possible to change only one source, and use a string directly instead of an array.
  "registry-mirrors": [
    "https://registry.docker-cn.com",
    "http://hub-mirror.c.163.com",
    "https://docker.mirrors.ustc.edu.cn"
  ],
}

# :wq Save and exit and restart docker
$ systemctl restart docker

2) Switch between Windows and Mac

Both Windows and Mac use Docker Desktop, so you can configure it directly in the GUI.

Open the Docker interface and click Docker Engine:

In the output box on the right, enter the mirror source:

{
    "registry-mirrors": [
        "https://registry.docker-cn.com",
        "http://hub-mirror.c.163.com",
        "https://docker.mirrors.ustc.edu.cn"
    ],
    }

4. Write Dockerfile

After installing Docker, we can then write our own project development environment. This article will take the front-end development environment as an example to build a Dockerfile.

Included environment:

  • Node.js 14.17
  • npm 6.14
  • yarn 1.22
# In front-end development, shell commands are often needed, and a relatively complete environment is more important, so Ubuntu is chosen as the basis. If you care about the size of the container, you can choose the appropriate basic image FROM ubuntu
LABEL org.opencontainers.image.authors="[email protected]"

# Set the environment variable ENV DEBIAN_FRONTEND noninteractive

# Set time zone ARG TZ=Asia/Shanghai
ENV TZ ${TZ}

RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone

# Use root user to operate USER root

# Change the Alibaba Cloud source to speed up the process in China RUN sed -i "s/security.ubuntu.com/mirrors.aliyun.com/" /etc/apt/sources.list && \
    sed -i "s/archive.ubuntu.com/mirrors.aliyun.com/" /etc/apt/sources.list && \
    sed -i "s/security-cdn.ubuntu.com/mirrors.aliyun.com/" /etc/apt/sources.list
RUN apt-get clean

# Update the source and install the corresponding tools RUN apt-get update && apt-get install -y \
    zsh \
    vim \
    wget \
    curl \
    python \
    git-core

# Install zsh so that you can use the shell more conveniently when you enter the container later
RUN git clone https://github.com/robbyrussell/oh-my-zsh.git ~/.oh-my-zsh && \
    cp ~/.oh-my-zsh/templates/zshrc.zsh-template ~/.zshrc && \
    git clone https://github.com/zsh-users/zsh-autosuggestions ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions && \
    git clone https://github.com/zsh-users/zsh-syntax-highlighting.git ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-syntax-highlighting && \
    sed -i 's/^plugins=(/plugins=(zsh-autosuggestions zsh-syntax-highlighting z /' ~/.zshrc && \
    chsh -s /bin/zsh

# Create me user RUN useradd --create-home --no-log-init --shell /bin/zsh -G sudo me && \
    adduser me sudo && \
    echo 'me:password' | chpasswd

# Install omz for me
USER me
RUN git clone https://github.com/robbyrussell/oh-my-zsh.git ~/.oh-my-zsh && \
    cp ~/.oh-my-zsh/templates/zshrc.zsh-template ~/.zshrc && \
    git clone https://github.com/zsh-users/zsh-autosuggestions ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions && \
    git clone https://github.com/zsh-users/zsh-syntax-highlighting.git ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-syntax-highlighting && \
    sed -i 's/^plugins=(/plugins=(zsh-autosuggestions zsh-syntax-highlighting z /' ~/.zshrc

# Install nvm and node
ENV NVM_DIR=/home/me/.nvm \
    NODE_VERSION=v14

RUN mkdir -p $NVM_DIR && \
    curl -o- https://gitee.com/mirrors/nvm/raw/master/install.sh | bash && \
    . $NVM_DIR/nvm.sh && \
    nvm install ${NODE_VERSION} && \
    nvm use ${NODE_VERSION} && \
    nvm alias ${NODE_VERSION} && \
    ln -s `npm bin --global` /home/me/.node-bin && \
    npm install --global nrm && \
    nrm use taobao && \
    echo '' >> ~/.zshrc && \
    echo 'export NVM_DIR="$HOME/.nvm"' >> ~/.zshrc && \
    echo '[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" # This loads nvm' >> ~/.zshrc

# Install yarn
RUN curl -o- -L https://yarnpkg.com/install.sh | bash; \
    echo '' >> ~/.zshrc && \
    echo 'export PATH="$HOME/.yarn/bin:$PATH"' >> ~/.zshrc

# Add NVM binaries to root's .bashrc
USER root

RUN echo '' >> ~/.zshrc && \
    echo 'export NVM_DIR="/home/me/.nvm"' >> ~/.zshrc && \
    echo '[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" # This loads nvm' >> ~/.zshrc && \
    echo '' >> ~/.zshrc && \
    echo 'export YARN_DIR="/home/me/.yarn"' >> ~/.zshrc && \
    echo 'export PATH="$YARN_DIR/bin:$PATH"' >> ~/.zshrc

# Add PATH for node & YARN
ENV PATH $PATH:/home/me/.node-bin:/home/me/.yarn/bin

# Delete apt/lists to reduce the final image size RUN rm -rf /var/lib/apt/lists/*

WORKDIR /var/www
After writing the Dockerfile, build it:

docker build -t frontend/react:v1 .
After building, you can run directly:

# Run as me, recommended method: docker run --user=me -it frontend/react:v1 /bin/zsh

# Run as root docker run -it frontend/react:v1 /bin/zsh

5. Write docker-compose.yml

During development, we usually need to use multiple containers together, such as mysql or other containers. Using docker-compose.yml can better organize them.

version: '2'
services:
    react:
    build:
        context: .
        dockerfile: react/Dockerfile
    tty: true
    ports:
        - 30000:3000
    volumes:
        - ./react/www:/var/www
    networks:
        -frontend
    mysql:
    image:mysql:5.7
    ports:
        - 33060:3306
    volumes:
        - ./mysql/data:/var/lib/mysql
        - ./mysql/docker-entrypoint-initdb.d:/docker-entrypoint-initdb.d
    environment:
        -MYSQL_ROOT_PASSWORD=password
    networks:
        -frontend

#Put the containers in the same networks and access the networks directly through the container name:
    frontend:
    driver: bridge

6. Start the container

After writing the above Dockerfile and docker-compose.yml, you can start development happily!

# Enter the directory where docker-compose.yml is located $ cd frontend

# Start all containers in docker-compose.yml in the background. If the container is not built, it will be built first. $ docker-compose up -d

# Enter the react container for command line interaction $ docker-compose exec --user=me react /bin/zsh

To test whether containers can access each other, you can write the following file. The database needs to be created by yourself:

// index.js
const mysql = require('mysql')
const connection = mysql.createConnection({
    host: 'mysql',
    user: 'root',
    password: 'password',
    database: 'test',
})

connection.connect();

connection.query(`SELECT * FROM users`, function (error, results, fields) {
    if (error) throw error;
    console.log(results)
})

connection.end();

Then run it and you can see the result:

$ node index.js
[ RowDataPacket { id: 1, name: 'Caster' } ]

7. Conclusion

It is very convenient to use Docker to build a development environment. Once built, it can be used multiple times on many machines. Even if you need to reinstall the system, you don’t have to repeat the configuration.

If you don’t like writing Dockerfile, you can also directly start a container, enter the container, configure it, and then use docker save/export to export it.

References:

1. Docker Tutorial

2. Docker builds a development environment

This concludes this article on how to use Docker to build a development environment (Windows and Mac). For more information about how to use Docker to build a development environment, please search for previous articles on 123WORDPRESS.COM or continue browsing the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed tutorial on how to use docker to build a laravel development environment in win10 home version
  • A detailed tutorial on using Docker to build a complete development environment
  • win10 docker-toolsbox tutorial on building a php development environment
  • Complete steps to build a Laravel development environment using Docker
  • Detailed explanation of how to install the laravel development environment with docker
  • Tutorial on configuring PHP development environment with Docker

<<:  Basic usage of JS date control My97DatePicker

>>:  MySQL data compression performance comparison details

Recommend

Nodejs-cluster module knowledge points summary and example usage

The interviewer will sometimes ask you, tell me h...

Detailed explanation of how to install PHP curl extension under Linux

This article describes how to install the PHP cur...

About uniApp editor WeChat sliding problem

The uniapp applet will have a similar drop-down p...

Mini Program to Implement Text Circular Scrolling Animation

This article shares the specific code of the appl...

Linux Disk Quota Management Graphical Example

Disk quota is the storage limit of a specified di...

Mysql 5.7.17 winx64 installation tutorial on win7

Software version and platform: MySQL-5.7.17-winx6...

Install and configure ssh in CentOS7

1. Install openssh-server yum install -y openssl ...

MySQL transaction details

Table of contents Introduction Four characteristi...

js to write the carousel effect

This article shares the specific code of js to ac...

Share 10 of the latest web front-end frameworks (translation)

In the world of web development, frameworks are ve...

Practical tutorial on modifying MySQL character set

Preface: In MySQL, the system supports many chara...