How to create a Dockerfile using Vim
Creating Dockerfiles easily without having to open a code editor, all from the terminal!
Vim is a powerful yet simple text editor used for editing text files inside the terminal. It is loved among programmers, system administrators and DevOps engineers for its adherence to ditching the mouse for keyboard shortcuts. Vim has interfaces such as normal mode (for navigating between the text) and insert mode (for writing text).
Dockerfiles contain instructions that allow us to build Docker images when the file is run. In your project, its name will be "Dockerfile".
Let's start
Firstly navigate to the root directory of your project in your terminal.
cd path/to/your/project
If you want to follow along with a test project, use Docker's official sample app:
git clone https://github.com/docker/getting-started-app.git
This is what the file structure of a basic Javascript project will look like, but a Dockerfile can be used in any project that you want to containerise.
├── getting-started-app/
│ ├── package.json
│ ├── README.md
│ ├── spec/
│ ├── src/
│ └── yarn.lock
Now, in the root directory, to create a Dockerfile with Vim we want to run:
vim Dockerfile
To enter insert mode, press the i
key on your keyboard. On the bottom of your Vim editor, it will say ~~INSERT~~
.
Enter the Dockerfile configurations for your specific project. This is just an example layout provided by Docker.
FROM node:18-alpine
WORKDIR /app
COPY . .
RUN yarn install --production
CMD ["node", "src/index.js"]
EXPOSE 3000
You may want to reference this article for writing good Dockerfiles.
Once you're happy with your configurations, press Esc
key to go back to normal mode.
In normal mode, press the :
key and type wq
The :
key tells Vim to recognise the following input as a command and wq
stands for write and quit (save and quit).
If you'd made a mistake while creating the Dockerfile then simply run vim Dockerfile
again to edit the file.
Note that you can also create a Docker compose file using this format, just repeat the process with vim docker-compose.yml
I hope you are now comfortable with creating a Dockerfile directly from the terminal by following this short article. Check out other #! terminal3 posts and feel free to message me on LinkedIn: My LinkedIn
Happy coding! ⌨️