One place for hosting & domains

      Linux

      How to Mount a File System on Linux


      Mounting or unmounting a file system on Linux is usually straightforward, except when it isn’t. This article teaches you how to mount and unmount file systems, as well as list available and currently mounted file systems. It also explains how to handle the case where file systems won’t unmount because they are in use.

    • You can list the currently mounted file systems from a Linux command line with a simple mount command:

      mount
      

      The following is on an Ubuntu 22.04 LTS Linode, logged in as root:

      sysfs on /sys type sysfs (rw,nosuid,nodev,noexec,relatime)
      proc on /proc type proc (rw,nosuid,nodev,noexec,relatime)
      udev on /dev type devtmpfs (rw,nosuid,relatime,size=441300k,nr_inodes=110325,mode=755,inode64)
      devpts on /dev/pts type devpts (rw,nosuid,noexec,relatime,gid=5,mode=620,ptmxmode=000)
      tmpfs on /run type tmpfs (rw,nosuid,nodev,noexec,relatime,size=99448k,mode=755,inode64)
      /dev/sda on / type ext4 (rw,relatime,errors=remount-ro)
      securityfs on /sys/kernel/security type securityfs (rw,nosuid,nodev,noexec,relatime)
      tmpfs on /dev/shm type tmpfs (rw,nosuid,nodev,inode64)
      tmpfs on /run/lock type tmpfs (rw,nosuid,nodev,noexec,relatime,size=5120k,inode64)
      cgroup2 on /sys/fs/cgroup type cgroup2 (rw,nosuid,nodev,noexec,relatime,nsdelegate,memory_recursiveprot)
      pstore on /sys/fs/pstore type pstore (rw,nosuid,nodev,noexec,relatime)
      bpf on /sys/fs/bpf type bpf (rw,nosuid,nodev,noexec,relatime,mode=700)
      systemd-1 on /proc/sys/fs/binfmt_misc type autofs (rw,relatime,fd=29,pgrp=1,timeout=0,minproto=5,maxproto=5,direct,pipe_ino=18031)
      hugetlbfs on /dev/hugepages type hugetlbfs (rw,relatime,pagesize=2M)
      mqueue on /dev/mqueue type mqueue (rw,nosuid,nodev,noexec,relatime)
      debugfs on /sys/kernel/debug type debugfs (rw,nosuid,nodev,noexec,relatime)
      tracefs on /sys/kernel/tracing type tracefs (rw,nosuid,nodev,noexec,relatime)
      fusectl on /sys/fs/fuse/connections type fusectl (rw,nosuid,nodev,noexec,relatime)
      configfs on /sys/kernel/config type configfs (rw,nosuid,nodev,noexec,relatime)
      none on /run/credentials/systemd-sysusers.service type ramfs (ro,nosuid,nodev,noexec,relatime,mode=700)
      tmpfs on /run/user/0 type tmpfs (rw,nosuid,nodev,relatime,size=99444k,nr_inodes=24861,mode=700,inode64)
    • You can list the static file system information by displaying /etc/fstab:

      cat /etc/fstab
      

      The two static file systems for this instance are the root disk and the swap disk:

      # /etc/fstab: static file system information.
      #
      # Use 'blkid' to print the universally unique identifier for a
      # device; this may be used with UUID= as a more robust way to name devices
      # that works even if disks are added and removed. See fstab(5).
      #
      # <file system> <mount point>   <type>  <options>       <dump>  <pass>
      /dev/sda        /               ext4    errors=remount-ro 0     1
      /dev/sdb        none            swap    sw                0     0
    • You can also list and search for file systems using the findmnt command:

      findmnt
      

      The basic output shows the file system tree:

      TARGET                                SOURCE     FSTYPE     OPTIONS
      /                                     /dev/sda   ext4       rw,relatime,errors=remount-ro
      ├─/sys                                sysfs      sysfs      rw,nosuid,nodev,noexec,relatime
      │ ├─/sys/kernel/security              securityfs securityfs rw,nosuid,nodev,noexec,relatime
      │ ├─/sys/fs/cgroup                    cgroup2    cgroup2    rw,nosuid,nodev,noexec,relatime,nsdelegate,memory_recursiveprot
      │ ├─/sys/fs/pstore                    pstore     pstore     rw,nosuid,nodev,noexec,relatime
      │ ├─/sys/fs/bpf                       bpf        bpf        rw,nosuid,nodev,noexec,relatime,mode=700
      │ ├─/sys/kernel/debug                 debugfs    debugfs    rw,nosuid,nodev,noexec,relatime
      │ ├─/sys/kernel/tracing               tracefs    tracefs    rw,nosuid,nodev,noexec,relatime
      │ ├─/sys/fs/fuse/connections          fusectl    fusectl    rw,nosuid,nodev,noexec,relatime
      │ └─/sys/kernel/config                configfs   configfs   rw,nosuid,nodev,noexec,relatime
      ├─/proc                               proc       proc       rw,nosuid,nodev,noexec,relatime
      │ └─/proc/sys/fs/binfmt_misc          systemd-1  autofs     rw,relatime,fd=29,pgrp=1,timeout=0,minproto=5,maxproto=5,direct,pipe_ino=18031
      ├─/dev                                udev       devtmpfs   rw,nosuid,relatime,size=441300k,nr_inodes=110325,mode=755,inode64
      │ ├─/dev/pts                          devpts     devpts     rw,nosuid,noexec,relatime,gid=5,mode=620,ptmxmode=000
      │ ├─/dev/shm                          tmpfs      tmpfs      rw,nosuid,nodev,inode64
      │ ├─/dev/hugepages                    hugetlbfs  hugetlbfs  rw,relatime,pagesize=2M
      │ └─/dev/mqueue                       mqueue     mqueue     rw,nosuid,nodev,noexec,relatime
      └─/run                                tmpfs      tmpfs      rw,nosuid,nodev,noexec,relatime,size=99448k,mode=755,inode64
        ├─/run/lock                         tmpfs      tmpfs      rw,nosuid,nodev,noexec,relatime,size=5120k,inode64
        ├─/run/credentials/systemd-sysusers.service
        │                                   none       ramfs      ro,nosuid,nodev,noexec,relatime,mode=700
        └─/run/user/0                       tmpfs      tmpfs      rw,nosuid,nodev,relatime,size=99444k,nr_inodes=24861,mode=700,inode64
    • You can restrict the output various ways, as described in man findmnt, to show only specific devices, mount points, or file system types, such as:

      findmnt -t ext4
      

      This lists only ext4 file systems:

      TARGET SOURCE   FSTYPE OPTIONS
      /      /dev/sda ext4   rw,relatime,errors=remount-ro
    • If you’re only interested in block devices, you can list them with lsblk:

      lsblk
      

      Once again, this only lists our Linode’s root and swap disks:

      NAME MAJ:MIN RM  SIZE RO TYPE MOUNTPOINTS
      sda    8:0    0 24.5G  0 disk /
      sdb    8:16   0  512M  0 disk [SWAP]
    • You can mount file systems for a single session using the mount command, and permanently by editing /etc/fstab. Mounting needs to be done by an administrator, either by logging in as root or by using the sudo command. There are some cases where mounting is done automatically, like when you insert a USB flash drive. Here are a few examples using the mount command, plus the preparatory mkdir command to create the mount point.

      Most modern distros automatically mount USB drives when you insert them.

      The network file system (NFS) supports mounting remote file systems as shares for local access.

      You can add the -l (lazy) switch to umount to instruct the system to unmount the device when it’s free. Alternatively, the -f (force) switch makes the system unmount the device right away, at the possible risk of corrupting the file system. The -f switch is primarily intended to unmount unreachable NFS shares.

      Mounting a file system on Linux is generally a straightforward two-step process: create a mount point directory, and use the mount command to mount the device at the mount point. Unless the file system is in use, unmounting is even simpler, requiring only the umount command. File system mounting and unmounting requires you to be logged in as root, or use the sudo prefix to temporarily take on root privileges.

      You may wish to consult the following resources for additional information
      on this topic. While these are provided in the hope that they will be
      useful, please note that we cannot vouch for the accuracy or timeliness of
      externally hosted materials.



      Source link

      How to Create a MERN Stack on Linux


      Of all the possible technical bases for a modern web site,
      “MERN holds the leading position when it comes to popularity.” This introduction makes you familiar with the essential tools used for a plurality of all web sites worldwide.

      Before You Begin

      1. If you have not already done so, create a Linode account and Compute Instance. See our
        Getting Started with Linode and
        Creating a Compute Instance guides.

      2. Follow our
        Setting Up and Securing a Compute Instance guide to update your system. You may also wish to set the timezone, configure your hostname, create a limited user account, and harden SSH access.

      Note

      The steps in this guide require root privileges. Be sure to run the steps below as root or with the sudo prefix. For more information on privileges, see our
      Users and Groups guide.

      What is the MERN stack?

      MERN refers to MongoDB, Express.js, ReactJS, and Node.js, four software tools which cooperate to power millions of web sites worldwide. In broad terms:

      • MongoDB manages data, such as customer information, technical measurements, and event records.
      • Express.js is a web application framework for the “behaviors” of particular applications. For example, how data flows from catalog to shopping cart.
      • ReactJS is a library of user-interface components for managing the visual “state” of a web application.
      • Node.js is a back-end runtime environment for the server side of a web application.

      Linode has
      many articles on each of these topics, and supports thousands of
      Linode customers who have created successful applications based on these tools.

      One of MERN’s important distinctions is the
      JavaScript programming language is used throughout the entire stack. Certain competing stacks use PHP or Python on the back end, JavaScript on the front end, and perhaps SQL for data storage. MERN developers focus on just a single programming language,
      JavaScript, with all the economies that implies, for training and tooling.

      Install the MERN stack

      You can install a basic MERN stack on a 64-bit x86_64
      Linode Ubuntu 20.04 host in under half an hour. As of this writing, parts of MERN for Ubuntu 22.04 remain experimental. While thousands of variations are possible, this section typifies a correct “on-boarding” sequence. The emphasis here is on “correct”, as scores of already-published tutorials embed enough subtle errors to block their use by readers starting from scratch.

      Install MongoDB

      1. Update the repository cache:

        apt update -y
        
      2. Install the networking and service dependencies Mongo requires:

        apt install ca-certificates curl gnupg2 systemctl wget -y
        
      3. Configure access to the official MongoDB Community Edition repository with the MongoDB public GPG key:

        wget -qO - https://www.mongodb.org/static/pgp/server-5.0.asc | apt-key add -
        
      4. Create a MongoDB list file:

        echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/5.0 multiverse" | tee /etc/apt/sources.list.d/mongodb-org-5.0.list
        
      5. Update the repository cache again:

        apt update -y
        
      6. Install MongoDB itself:

        apt install mongodb-org -y
        
      7. Enable and the MongoDB service:

        systemctl enable mongod
        
      8. Launch the MongoDB service:

        systemctl start mongod
        
      9. Verify the MongoDB service:

        systemctl status mongod
        

        You should see diagnostic information that concludes:

        … Started MongoDB Database Server.
        
      10. For an even stronger confirmation that the Mongo server is ready for useful action, connect directly to it and issue this command:

        mongo
        
      11. Now issue this command:

        db.runCommand({ connectionStatus: 1 })
        

        You should see, along with many other details, this summary of the connectionStatus:

        … MongoDB server … "ok" : 1 …
        
      12. Exit Mongo:

         exit
        

      Install Node.js

      While the acronym is MERN, the true order of its dependencies is better written as “MNRE”. ReactJS and Express.js conventionally require Node.js, so the next installation steps focus on Node.js. As with MongoDB, Node.js’s main trusted repository is not available in the main Ubuntu repository.

      1. Run this command to adjoin it:

        curl -sL https://deb.nodesource.com/setup_16.x | bash -
        
      2. Install Node.js itself:

        apt-get install nodejs -y
        
      3. Verify the installation:

        node -v
        

        You should see v16.15.1 or perhaps later.

      Install React.js

      1. Next, install React.js:

        mkdir demonstration; cd demonstration
        npx --yes create-react-app frontend
        cd frontend
        npm run build
        

      Templates for all the HTML, CSS, and JS for your model application are now present in the demonstration/frontend directory.

      Install Express.js

      1. Express.js is the final component of the basic MERN stack.

        cd ..; mkdir server; cd server
        npm init -y
        cd ..
        npm install cors express mongodb mongoose nodemon
        

      Use the MERN stack to create an example application

      The essence of a web application is to respond to a request from a web browser with an appropriate result, backed by a datastore that “remembers” crucial information from one session to the next. Any realistic full-scale application involves account management, database backup, context dependence, and other refinements. Rather than risk the distraction and loss of focus these details introduce, this section illustrates the simplest possible use of MERN to implement a
      three-tier operation typical of real-world applications.

      “Three-tier” in this context refers to the teamwork web applications embody between:

      • The presentation in the web browser of the state of an application
      • The “back end” of the application which realizes that state
      • The datastore which supports the back end beyond a single session of the front end or even the restart of the back end.

      You can create a tiny application which receives a request from a web browser, creates a database record based on that request, and responds to the request. The record is visible within the Mongo datastore.

      Initial configuration of the MERN application

      1. Create demonstration/server/index.js with this content:

        const express = require('express');
        const bodyParser = require('body-parser');
        const mongoose = require('mongoose');
        const routes = require('../routes/api');
        const app = express();
        const port = 4200;
        
        // Connect to the database
        mongoose
          .connect('mongodb://127.0.0.1:27017/', { useNewUrlParser: true })
          .then(() => console.log(`Database connected successfully`))
          .catch((err) => console.log(err));
        
        // Override mongoose's deprecated Promise with Node's Promise.
        mongoose.Promise = global.Promise;
        app.use((req, res, next) => {
          res.header('Access-Control-Allow-Origin', '*');
          res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
            next();
          });
          app.use(bodyParser.json());
          app.use('/api', routes);
          app.use((err, req, res, next) => {
            console.log(err);
            next();
          });
        
          app.listen(port, () => {
            console.log(`Server runs on port ${port}.`);
          });
        
      2. Create demonstration/routes/api.js with this content:

        const express = require('express');
        const router = express.Router();
        
        var MongoClient = require('mongodb').MongoClient;
        var url="mongodb://127.0.0.1:27017/";
        const mongoose = require('mongoose');
        var db = mongoose.connection;
        
        router.get('/record', (req, res, next) => {
          item = req.query.item;
          MongoClient.connect(url, function(err, db) {
            if (err) throw err;
            var dbo = db.db("mydb");
            var myobj = { name: item };
            dbo.collection("demonstration").insertOne(myobj, function(err, res) {
              if (err) throw err;
              console.log(`One item (${item}) inserted.`);
              db.close();
            })
          });
        })
        module.exports = router;
        
      3. Create demonstration/server/server.js with this content:

        const express = require("express");
        const app = express();
        const cors = require("cors");
        require("dotenv").config({ path: "./config.env" });
        const port = process.env.PORT || 4200;
        app.use(cors());
        app.use(express.json());
        app.use(require("./routes/record"));
        const dbo = require("./db/conn");
        
        app.listen(port, () => {
          // Connect on start.
          dbo.connectToServer(function (err) {
            if (err) console.error(err);
          });
          console.log(`Server is running on port: ${port}`);
        });
        

      Verify your application

      1. Launch the application server:

        node server/index.js
        
      2. In a convenient Web browser, request:

        localhost:4200/api/record?item=this-new-item
        

        At this point, your terminal should display:

        One item (this-new-item) inserted.
        
      3. Now launch an interactive shell to connect to the MongoDB datastore:

        mongo
        
      4. Within the MongoDB shell, request:

        use mydb
        db.demonstration.find({})
        

        Mongo should report that it finds a record:

        { "_id" : ObjectId("62c84fe504d6ca2aa325c36b"), "name" : "this-new-item" }
        

      This demonstrates a minimal MERN action:

      • The web browser issues a request with particular data.
      • The React front end framework routes that request.
      • The Express application server receives the data from the request, and acts on the MongoDB datastore.

      Conclusion

      You now know how to install each of the basic components of the MERN stack on a standard Ubuntu 20.04 server, and team them together to demonstrate a possible MERN action: creation of one database record based on a browser request.

      Any real-world application involves considerably more configuration and source files. MERN enjoys abundant tooling to make the database and web connections more secure, to validate data systematically, to structure a
      complete Application Programming Interface (API), and to simplify debugging. Nearly all practical applications need to create records, update, delete, and list them. All these other refinements and extensions use the elements already present in the workflow above. You can build everything your full application needs from this starting point.

      More Information

      You may wish to consult the following resources for additional information
      on this topic. While these are provided in the hope that they will be
      useful, please note that we cannot vouch for the accuracy or timeliness of
      externally hosted materials.



      Source link

      How to Rename Files on Linux


      Windows and macOS users often manage their files using the Graphical User Interface (GUI) file manager provided on their systems. Typically Windows File Explorer or macOS Finder, respectively. Linux systems also usually have a GUI file manager, such as Dolphin, Nautilus, or Thunar. However, when managing a remote server, you may not have access to the GUI. It can be incredibly frustrating trying to figure out command line file operations while typing at an SSH, LISH, or other command line prompt. Fortunately, the commands are straightforward once you understand them.

      This tutorial primarily discusses how to use the mv and rename commands to rename one or more files in a terminal session. Creating files and displaying your Linux file system using the touch and ls commands are also covered.

      Before You Begin

      For the purposes of this tutorial, a shared instance with 1 CPU and 1 GB of memory running Ubuntu 22.04 LTS works. Pick a region that is close to your location. Create a strong root password and save it for later. Should you ever forget your root password, you can create a new one on your settings page. Don’t bother creating a SSH key for the account unless you’re already familiar with RSA keys.

      1. If you have not already done so, create a Linode account and Compute Instance. See our
        Getting Started with Linode and
        Creating a Compute Instance guides.

      2. Follow our
        Setting Up and Securing a Compute Instance guide to update your system. You may also wish to set the timezone, configure your hostname, create a limited user account, and harden SSH access.

      Note

      The steps in this guide require root privileges. Be sure to run the steps below as root. For more information on privileges, see our
      Users and Groups guide.
      1. When your new Linode is running, click on the Launch LISH Console button.

      2. Once the Weblish side of the display has stopped scrolling, click on the Glish side of the display.

      3. Log in as root with the password you chose in the previous step.

      Renaming Files Using mv

      Short for “move”, the mv command moves files from one directory to another, but it also renames single files.

      1. From the root directory, type:

        ls
        

        You should have no results, as there are no visible files in the root directory.

      2. However, there are hidden files, to reveal them, type:

        ls -a
        

        You should now see a handful of hidden files:

        . .. .bashrc .cache .profile .ssh
        
      3. Create an empty file:

        touch test.txt
        
      4. View the directory again:

        ls
        

        Your test file should now be listed:

        test.txt
        
      5. Rename the file:

        mv test.txt test1.txt
        
      6. View the directory again:

        ls
        

        Your test file should now be listed with a different filename:

        test1.txt
        

      Rename File(s) Using the rename Command

      While the mv command
      can be used inside a shell loop to rename multiple files, that requires some advanced text substitution. Instead, you can use a different command, rename.

      If your Ubuntu Linode is brand new, it probably doesn’t have the rename command installed.

      1. First, update your package sources:

        apt update
        
      2. Now install rename:

        apt install rename
        
      3. Once installed, create a second file with touch:

        touch test2.txt
        
      4. List both of them:

        ls
        

        You should now see both files:

        test1.txt test2.txt
        

      Note

      rename uses a Perl expression to act on the file names. Run man rename for an explanation and several examples.

      1. As an example, let’s rename both text files to backup files:

        rename 's/txt/bak/' *.txt
        

        Note

        On CentOS Stream 9, use this command instead:

        rename .txt .bak *.txt
        
      2. Now list them:

        ls
        

        You should see the same files as before, but with .bak extensions:

        test1.bak test2.bak
        

      When you’re done with this exercise, exit the LISH shell. If you don’t need this Linode anymore, delete it from its settings in the &mldr; dropdown menu to avoid incurring future charges.

      Conclusion

      Renaming a single file on a terminal in Ubuntu Linux is accomplished with the mv command. Renaming multiple files is accomplished with the rename command, which you have to install in a new instance of Ubuntu 22.04 LTS.



      Source link