[작성자:] Saturn

  • ubuntu update and upgrade

    ubuntu update and upgrade

    1. Update and Upgrade

    To keep Ubuntu up to date, use the update or upgrade command. Update and upgrade may be the same, but there is a difference. The update command does not change the package to the latest version, but instead retrieves information about the latest version available on the system.

    Original Korean article: ubuntu update and upgrade

    That is, it does not download or install any packages. You must use the upgrade command to download and install the package. The system operates on a database of available packages.

    The database does not contain packages, only the package’s metadata (version, repositories, dependencies, etc.). So without updating the database the system won’t know whether there is a newer package available or not.

    Update and upgrade are administrative commands and must be executed with root privileges. sudo allows you to run commands as Ubuntu root. So I log in as root or use sudo for both commands.

    1) apt update

    Get updated metadata from a package with the apt update command. Your local package cache will be updated and you will see which packages are available for upgrade.

    apt update: Updates the package cache (knows which package versions can be installed or upgraded)

    • package update
    sudo apt update

    You can use the apt and apt-get commands to update the package cache. The two commands are the same, but the difference is that the apt command displays the number of upgradeable packages. Here it shows that there are 59 upgradeable packages.

    sudo apt update
    sudo apt update

    2) apt upgrade

    You can upgrade all (upgradable) packages with sudo apt upgrade. You can press Enter or Y to proceed with the upgrade, or press N to cancel.

    apt upgrade: Upgrade a package to a new version

    • View package upgrade list
    sudo apt list --upgradeable

    You can upgrade the entire package with the sudo get upgrade command, but before that, you can check the list of packages that can be upgraded.

    sudo apt list --upgradeable
    sudo apt list –upgradeable
    sudo apt upgrade
    sudo apt upgrade
    • package upgrade
    sudo apt upgrade

    Before the upgrade begins, you will be asked whether you want to continue. Type Y to proceed with the upgrade, n to cancel, and then press enter. Here, type Y to proceed with the upgrade and proceed.

    sudo apt upgrade
    sudo apt upgrade
    sudo apt upgrade
    sudo apt upgrade

    When the upgrade is complete, a window will appear asking you to restart the service. Here we select OK and continue. When the upgrade is complete, you can check the restarted services.

    sudo apt upgrade
    sudo apt upgrade

    If you re-enter the sudo apt update command, you can see that there are no upgradeable packages.

    sudo apt upgrade
    sudo apt upgrade

    Good article to read together

    • VirtualBox Virtual Box virtual machine download and installation
    • Download Ubuntu and set up Ubuntu (virtualbox)
    • Install Ubuntu 22.04.1 (VirtualBox)
    • Install and enable Ubuntu firewall iptables
    • Ubuntu firewall iptables setup and management

    Related Reading

    Continue with these related Thinknote English articles in the Server & Infrastructure cluster.

    FAQ

    What is this article about?

    This article is part of Thinknote’s English server and infrastructure archive. It focuses on practical Linux, Ubuntu, web-server, database, SSH, firewall, or hosting operations that readers can adapt to their own environment.

    How should I use this guide?

    Use it as a practical checklist and concept guide. Before applying commands on a live server, verify package names, OS versions, ports, and backup requirements for your own setup.

    Where can I read the original Korean article?

    The original Korean article is available here: Original Korean article.

  • Install and enable Ubuntu firewall iptables

    Firewall covers installing and activating iptables as an important step in server security. A large part of firewall management involves determining the individual rules and policies that will apply traffic restrictions to your network.

    Original Korean article: Install and enable Ubuntu firewall iptables

    1. Understanding iptables firewall and preparing in advance

    Ubuntu provides ufw as a default firewall, but iptables allows detailed management of the structural framework to which rules are applied.

    First, stop using the ufw firewall and configure the firewall using the iptables package. iptables focuses on establishing a framework that provides reasonable defaults and encourages extensibility.

    1) Advance preparation

    Check the ufw firewall status and stop the firewall. If you followed along with the Ubuntu installation, the ufw firewall is active. At this time, if you enter the sudo ufw status command, it will display inactive. If you install iptables and do not disable the ufw firewall, a conflict will occur. Commands for managing services can be managed in the form of systemctl or [service name.service].

    2) Check ufw status

    sudo systemctl status ufw
    Article image 1
    Article image 1

    3) stop and disable ufw

    You can utilize the stop command to stop a service, but stop does not affect startup activation. On the other hand, the disable command disables the service at startup, and adding the –now command takes effect immediately. Disable the ufw service with the command below and restart it with the reboot command.

    sudo systemctl disable --now ufw
    reboot
    Article image 2
    Article image 2
    sudo systemctl status ufw
    Article image 3
    Article image 3

    2. Check for iptables installation and activation issues

    1) Install iptables (iptables-persistent)

    If you have stopped ufw, install the iptables package. After installing Iptables, you can save your rule sets and have them automatically applied at boot.

    sudo apt install iptables-persistent
    Article image 4
    Article image 4
    Article image 5
    Article image 5
    Article image 6
    Article image 6

    2) Enable iptables when starting

    • Check IPtables status
    sudo systemctl status iptables
    Article image 7
    Article image 7
    • Iptables status active on startup
    sudo systemctl enable iptables
    reboot
    Article image 8
    Article image 8

    3) Check iptables activation issue (not automatically activated on startup)

    • Check IPtables status

    It is activated normally in Ubuntu 20, but is not activated in Ubuntu 22. If you check the status of iptables, the alias is not registered, so you need to register the alias.

    sudo systemctl status iptables
    Article image 9
    Article image 9

    3. Register an iptables alias and activate it at startup

    1) Register an alias to activate Iptables startup

    You can check the location of iptables.service in the status and load the file with the nano editor. You can also use the vi editor. Register the alias under [install] at the bottom of the file. Here, register as Alias=iptables.service.

    sudo nano /lib/systemd/system/iptables.service
    Article image 10
    Article image 10
    Article image 11
    Article image 11

    Disable Iptables and then re-enable it. At this time, if you add the –now command, the service will run together with activation.

    sudo systemctl disable iptables
    sudo systemctl enable iptables

    2) Check service activation after restart

    Restart the server to see if the service is enabled at startup. As shown in the image below, if a dependency conflict occurs with netfilter-persistent.service, restart netfilter-persistent.service. You can check that the iptables service is properly activated using the systemctl command.

    reboot
    sudo systemctl status iptables
    sudo systemctl restart netfilter-persistent.service
    Article image 12
    Article image 12

    3. iptables block all connections

    The previous setting is a setting where INPUT, FORWARD, and OUTPUT are all allowed. I will close all INPUT and FORWARD. When I output the configuration, INPUT and FORWARD are marked as closed. If services are added in the future, only the ports for the relevant services will be opened and run.

    sudo iptables -P INPUT DROP
    sudo iptables -P FORWARD DROP
    sudo iptables -S
    Article image 13
    Article image 13

    Save the changed settings and reload. reload is a command to apply rules without restarting. Any changes you make will not take effect when Ubuntu restarts unless you run the following code.

    sudo netfilter-persistent save
    sudo netfilter-persistent reload

    Good article to read together

    • Ubuntu firewall iptables setup and management
    • Install Nginx web server (ubuntu)
    • Linux administrator tool – enable cockpit
    • Activate Centos 8 RHEL & REMI Repository
    • Install Nginx web server (Centos 8)

    Related Reading

    Continue with these related Thinknote English articles in the Server & Infrastructure cluster.

    FAQ

    What is this article about?

    This article is part of Thinknote’s English server and infrastructure archive. It focuses on practical Linux, Ubuntu, web-server, database, SSH, firewall, or hosting operations that readers can adapt to their own environment.

    How should I use this guide?

    Use it as a practical checklist and concept guide. Before applying commands on a live server, verify package names, OS versions, ports, and backup requirements for your own setup.

    Where can I read the original Korean article?

    The original Korean article is available here: Original Korean article.

  • Ubuntu iptables Firewall Management: Practical Setup and Commands

    Ubuntu iptables Firewall Management: Practical Setup and Commands

    This guide is a fuller English adaptation of the original Korean Ubuntu iptables article. The source post is a practical server-administration note, not just a short firewall overview. It explains how to understand iptables, check rules, flush chains, add local and inbound rules, save changes, and read common iptables command options.

    Ubuntu iptables firewall setup
    Ubuntu iptables firewall setup.

    Original Korean article: Ubuntu 방화벽 iptables 설정 및 관리

    1. Understanding iptables Firewall Management on Ubuntu

    checking current iptables rules
    checking current iptables rules.

    Firewall management is the process of deciding which network traffic should be allowed, rejected, or dropped. Ubuntu often provides UFW as a user-friendly firewall interface, but iptables gives administrators a more detailed view of the rule structure behind packet filtering.

    iptables is useful because it helps you understand chains, rules, policies, interfaces, ports, and connection states. Even if you later use UFW or nftables, learning iptables improves your understanding of Linux server security.

    The original tutorial proceeds by disabling UFW and configuring the firewall directly through iptables. The goal is to build a reasonable, extensible framework rather than blindly copying a single command.

    2. Initial iptables Setup Strategy

    adding inbound firewall rules
    adding inbound firewall rules.

    A firewall can be configured in two broad ways. The first approach is to allow most traffic and block only known unwanted traffic. The second approach is to define allowed traffic and block everything else. For cloud servers and production-like systems, the second approach is usually safer because it reduces accidental exposure.

    However, restrictive firewall rules can also lock you out of your own server. Before applying strict rules, always make sure SSH access is allowed and that you have a recovery method from the hosting console or virtual machine interface.

    1) Check current iptables rules

    Before changing anything, check the current rules. The original article explains that the -L option lists rules in chains, while the -S option prints rules in a format closer to commands. Both are useful.

    The basic chains include INPUT, OUTPUT, and FORWARD. INPUT applies to packets coming into the local server. OUTPUT applies to packets leaving the server. FORWARD applies to packets routed through the server rather than delivered locally.

    Other chains such as PREROUTING and POSTROUTING appear in routing and NAT contexts. PREROUTING processes packets before routing decisions. POSTROUTING processes packets after routing decisions and before packets leave through network hardware.

    2) Flush existing rules carefully

    The original tutorial shows how to remove existing rules with options such as -F and -X. The -F option flushes rules from chains, while -X deletes user-defined chains.

    This is useful in a learning environment or clean setup, but it must be used carefully on a remote server. If you remove rules and then apply a default drop policy without allowing SSH, you may lose access.

    3) Add loopback and local traffic rules

    Local loopback traffic should normally be allowed. The loopback interface is used by services on the same machine to communicate internally. Blocking it can break software that expects local connections to work.

    iptables rules can be appended with -A, and interfaces can be specified with -i. This allows administrators to distinguish local loopback traffic from external network traffic.

    4) Add inbound traffic rules

    To begin using iptables safely, add allowed inbound rules for required services. For example, a server may need SSH, HTTP, HTTPS, or application-specific ports. The original article also highlights connection states such as RELATED and ESTABLISHED.

    Allowing established connections means that replies to already-approved connections can continue. This is important because server communication is not only about new inbound requests; it also includes packets that belong to existing sessions.

    5) Save and restart rules

    Adding rules in a session does not automatically make them persistent after reboot. The original article explains the need to save changes and reload or restart related services. On Ubuntu systems, tools such as netfilter-persistent can be used to save, reload, restart, start, stop, or flush persistent rules.

    A good practice is to save rules only after confirming that SSH and required services still work. After saving, reboot or reload in a controlled way and verify the active rules again.

    3. Basic iptables Command Forms

    saving iptables rules
    saving iptables rules.

    The source article lists common command forms. Administrators use -A to append rules, -I to insert rules at a specific position, -R to replace rules, -D to delete rules, -L to list rules, -S to print rules, -F to flush chains, -N to create a chain, -X to delete a chain, -E to rename a chain, and -P to set a default policy.

    These options matter because rule order matters. A packet is checked against rules in sequence. If an early rule matches, later rules may not be evaluated in the way a beginner expects. This is why inserting, replacing, and listing rules are daily administration tasks.

    4. Common iptables Options and Rule Management

    iptables port management
    iptables port management.

    The original article includes command options such as append, check, delete, insert, replace, list, list-rules, flush, zero counters, new chain, delete chain, policy, protocol, source, destination, input interface, output interface, jump target, and match extensions.

    For practical server work, you should understand at least five ideas: what chain the rule belongs to, what protocol it matches, what source or destination it applies to, what port it affects, and what target action it takes. A target may accept, drop, reject, or jump to another chain.

    5. Ports, SSH, and Web Server Access

    The tutorial connects iptables to port usage. SSH commonly uses port 22 unless changed. Web servers commonly use port 80 for HTTP and 443 for HTTPS. Database and internal service ports should usually not be exposed publicly unless there is a specific reason and additional protection.

    A safe firewall mindset is minimal exposure. Open only what the server needs. Document why each port is open. Recheck rules after installing services such as Nginx, PHP, Redis, or database tools.

    Practical Safety Checklist

    Before applying iptables rules on a remote Ubuntu server, check the current rules, confirm SSH access, allow loopback traffic, allow established connections, open required service ports, apply rules gradually, save only after verification, and keep a recovery path available.

    iptables can look complex at first, but it becomes manageable when treated as a structured decision table for network traffic. The value of the original article is that it walks through the mindset and command categories needed for real server operation.

    Related Reading

    Continue with these related Thinknote English articles in the Server & Infrastructure cluster.

    FAQ

    What is this article about?

    This article is part of Thinknote’s English server and infrastructure archive. It focuses on practical Linux, Ubuntu, web-server, database, SSH, firewall, or hosting operations that readers can adapt to their own environment.

    How should I use this guide?

    Use it as a practical checklist and concept guide. Before applying commands on a live server, verify package names, OS versions, ports, and backup requirements for your own setup.

    Where can I read the original Korean article?

    The original Korean article is available here: Ubuntu iptables Firewall Management: Practical Setup and Commands.

  • Ubuntu OpenSSH and MobaXterm Setup: Remote Server Access Guide

    Ubuntu OpenSSH and MobaXterm Setup: Remote Server Access Guide

    This guide is a fuller English adaptation of the original Korean article about installing OpenSSH on Ubuntu and using MobaXterm for remote access. The source post explains the SSH protocol, OpenSSH features, installation checks, server packages, and MobaXterm installation for Windows users.

    Ubuntu OpenSSH concept and setup
    Ubuntu OpenSSH concept and setup.

    Original Korean article: Ubuntu OpenSSH 설치 및 MobaXterm 설치

    1. What OpenSSH Is and Why It Matters

    installing OpenSSH on Ubuntu
    installing OpenSSH on Ubuntu.

    OpenSSH and the SSH protocol

    SSH is a secure protocol for remote login and remote command execution. Compared with older tools such as telnet and rlogin, SSH provides encrypted communication and stronger authentication. This is why SSH is a basic requirement for Linux server administration.

    The original article notes that SSH1 is no longer supported in modern OpenSSH releases, while SSH2 was developed to improve security, avoid earlier patent issues, and address data integrity problems. SSH2 supports a variety of symmetric and asymmetric cryptographic choices.

    OpenSSH is one of the most widely used tools for SSH-based remote access. It encrypts traffic to reduce the risk of eavesdropping, connection hijacking, and other network attacks. It also supports tunneling, multiple authentication methods, and detailed configuration options.

    Tools included in the OpenSSH family

    The OpenSSH suite includes client and server tools. Remote work can be performed with ssh, scp, and sftp. Key management involves tools such as ssh-add, ssh-keysign, ssh-keyscan, and ssh-keygen. The service side includes sshd, sftp-server, and ssh-agent.

    2. Key Features of OpenSSH

    checking SSH service status
    checking SSH service status.

    Open source and widely usable

    OpenSSH is an open source project that can be used freely, including in commercial contexts. Because the code is public, it benefits from review, reuse, bug discovery, and long-term maintenance by a broad community.

    Strong encryption before authentication

    OpenSSH starts encryption before authentication, which helps prevent passwords and other sensitive information from being sent in plain text. It supports modern algorithms and key types such as AES, ChaCha20, RSA, ECDSA, and Ed25519, while older options are gradually removed or discouraged.

    X11 forwarding

    X11 forwarding allows remote graphical traffic to be sent through an encrypted SSH channel. This can be useful when running graphical applications from a remote Unix-like environment while reducing the risk of someone snooping on the session or injecting commands into an unprotected connection.

    Port forwarding for secure tunnels

    Port forwarding creates encrypted channels for TCP/IP connections. This can protect legacy services or internal tools by routing them through SSH. For example, insecure protocols can be wrapped in an encrypted tunnel when a direct secure alternative is not available.

    Strong authentication methods

    OpenSSH supports authentication methods such as public keys, one-time passwords, and in some environments Kerberos. Public key authentication is especially common for server administration because it reduces reliance on reusable passwords and can be combined with passphrases and agents.

    Agent forwarding and compression

    Agent forwarding lets a local authentication agent hold keys and forward authentication through an SSH connection without storing private keys on every remote system. OpenSSH also supports optional compression, which can improve performance over slower network links.

    3. Installing and Checking OpenSSH on Ubuntu

    MobaXterm download and install
    MobaXterm download and install.

    If Ubuntu was installed with server features, SSH may already be installed. The original tutorial checks service status with systemctl. Even if the package is installed, you should confirm that the service is running and enabled.

    OpenSSH usually runs as ssh.service on Ubuntu. The installed package list may include openssh-client, openssh-server, and an SFTP server package. For remote login into the Ubuntu machine, openssh-server is essential.

    After installation, enable the service so that it starts automatically on boot. Then reboot or restart the service in a controlled way and verify that SSH is still available.

    4. Preparing MobaXterm for SSH Access from Windows

    connecting to Ubuntu server with SSH
    connecting to Ubuntu server with SSH.

    Why MobaXterm is useful

    MobaXterm is a remote access program for Windows. It is convenient for programmers, webmasters, and IT administrators because it combines SSH sessions with additional remote network tools. It can provide SSH, X11, RDP, VNC, FTP, MOSH, and Unix-like commands from a Windows desktop environment.

    When connecting to a remote server through SSH, MobaXterm can automatically show a graphical SFTP browser. This makes it easier for beginners to inspect and edit remote files while also using a terminal session.

    Download and install MobaXterm

    The original article downloads MobaXterm from the official Home Edition page and proceeds with the installer edition rather than the portable edition. After downloading, unzip or run the installer package and complete the installation wizard.

    After launching MobaXterm, you can create an SSH session by entering the server address, username, and port. If SSH uses a non-default port, the client setting must match the server configuration and firewall rules.

    5. Connection Checks Before Remote Work

    Remote access depends on several conditions working together: the server IP address is correct, OpenSSH server is installed, ssh.service is running, the firewall allows the SSH port, the username exists, and the authentication method is valid.

    If connection fails, do not assume the client is the problem. Check service status, port configuration, firewall rules, network reachability, and credentials. In server administration, connection troubleshooting is often a chain of small checks.

    6. Security After the First Successful Login

    Once SSH works, improve security. Use strong passwords or public key authentication, limit unnecessary users, keep packages updated, document the port, and avoid exposing other services without need. Remote access should be convenient enough to operate but strict enough to protect the server.

    The original article connects this topic to related Ubuntu setup tasks such as SSH port configuration, VirtualBox installation, Ubuntu installation, update and upgrade, and firewall settings. OpenSSH is often the gateway to all later Linux server work.

    Related Reading

    Continue with these related Thinknote English articles in the Server & Infrastructure cluster.

    FAQ

    What is this article about?

    This article is part of Thinknote’s English server and infrastructure archive. It focuses on practical Linux, Ubuntu, web-server, database, SSH, firewall, or hosting operations that readers can adapt to their own environment.

    How should I use this guide?

    Use it as a practical checklist and concept guide. Before applying commands on a live server, verify package names, OS versions, ports, and backup requirements for your own setup.

    Where can I read the original Korean article?

    The original Korean article is available here: Ubuntu OpenSSH and MobaXterm Setup: Remote Server Access Guide.

  • Setting up and connecting Ubuntu SSH ports

    Setting up and connecting Ubuntu SSH ports

    1. Open Ubuntu SSH port

    To open the SSH port, you need to do two things. First, you need to open port 22 to Ubuntu iptables, and second, you need to forward the port of virtualbox. If you installed Ubuntu using an external IP, you can just do the first step. If the host PC is connected to the router, you must connect port 22 to the host PC through DMZ settings and port forwarding to be able to access it from outside.

    Original Korean article: Setting up and connecting Ubuntu SSH ports

    1) Basic environment configuration

    The content starting from now on assumes the following environment.

    • Ubuntu is installed as virtual
    • The host PC is assigned an IP from the internal router.
    • Virtual IP: 10.0.2.15

    2) Allow Iptables SSH port

    SSH port uses 22. Open IPtables to use TCP port 22.

    • -A : Add to chain
    • -p tcp : protocol tcp
    • -m tcp: tcp match, extended match
    • –dport: Port number
    • — j : Jump to target
    • ACCEPT: Allow
    sudo iptables -A INPUT -p tcp -m tcp --dport 22 -j ACCEPT

    Prints rules to see if the chain is registered in iptables. Save the added rules and reload.

    sudo iptables -S
    sudo netfilter-persistent save
    sudo netfilter-persistent reload
    Article image 1
    Article image 1

    Let’s check the IP of ubuntu. When you check the IP using the ip addr command, the following output appears and it is confirmed that Ubuntu’s IP is 10.0.2.15.

    ip addr
    Article image 2
    Article image 2

    2. SSH port forwarding in VirtualBox

    Opening Ubuntu’s SSH port allows Ubuntu to connect, but connection is not yet possible from the host computer. To connect to Ubuntu using MobaXterm on the host computer, you need to forward the port in VirtualBox.

    In VirtualBox, you can enable port foreclosure in the settings without shutting down the virtual machine. Click Network in Virtual PC Settings.

    virtualbox ssh
    virtualbox ssh
    virtualbox ssh
    virtualbox ssh

    Expand Network Advanced and click the Port Forwarding button.

    virtualbox ssh
    virtualbox ssh

    Click the plus icon at the top right to add a port forwarding rule. Enter the name [SSH], protocol [TCP], host IP (you can leave it blank because you are connecting as a local host) [ ], host port [22], guest IP (ubuntu IP can be checked with the ip addr command) [10.0.2.15], and guest port [22].

    virtualbox ssh
    virtualbox ssh

    3. Access Ubuntu terminal using MobaXterm

    Run MobaXterm. Since there are no registered sessions yet, click Session at the top left to register a new session.

    mobaxterm ssh
    mobaxterm ssh

    To connect to Ubuntu using SSH, click SSH in the upper left corner.

    mobaxterm ssh
    mobaxterm ssh

    Remnote Host refers to the IP of the host PC, not the ubuntu IP. The Host IP can be checked by running the terminal on the host PC using the cmd command and using the ipconfig /all command. Since we are connecting using localhost IP here, we will enter 127.0.0.1. Click the OK button to close the window.

    mobaxterm ssh
    mobaxterm ssh

    You can see that the 127.0.0.1 session has been added to the user session section on the left side of MobaXterm. If you double-click the session and the login terminal appears, the port is normally open.

    mobaxterm ssh
    mobaxterm ssh

    Good article to read together

    • Install Ubuntu OpenSSH and install MobaXterm
    • VirtualBox Virtual Box virtual machine download and installation
    • Download Ubuntu and set up Ubuntu (virtualbox)
    • Install Ubuntu 22.04.1 (VirtualBox)
    • firewall settings

    Related Reading

    Continue with these related Thinknote English articles in the Server & Infrastructure cluster.

    FAQ

    What is this article about?

    This article is part of Thinknote’s English server and infrastructure archive. It focuses on practical Linux, Ubuntu, web-server, database, SSH, firewall, or hosting operations that readers can adapt to their own environment.

    How should I use this guide?

    Use it as a practical checklist and concept guide. Before applying commands on a live server, verify package names, OS versions, ports, and backup requirements for your own setup.

    Where can I read the original Korean article?

    The original Korean article is available here: Original Korean article.

  • Install Nginx web server (ubuntu)

    Install Nginx web server (ubuntu)

    1. Nginx web server Vs Apache web server

    Here we proceed with installing the Nginx web server. Web servers installed on Linux are divided into Nginx web servers and Apache web servers, and have the following differences. Apache is an open source HTTP server, while Nginx is an open source, high-performance asynchronous web server and reverse proxy server.

    Original Korean article: Install Nginx web server (ubuntu)

    While the development and evolution of Apache HTTP Server is managed and maintained by a worldwide user community (Apache Software Foundation), Nginx is maintained and maintained by the company of the same name, founded in 2011.

    While Apache provides various multiprocessing modules to handle client requests and web traffic, Nginx is designed to handle multiple client requests simultaneously with minimal hardware resources.

    In Apache, a single thread is associated with one connection, but in Nginx, a single thread can handle multiple connections. This process consumes less memory and improves performance.

    While Apache HTTP Server has a non-scalable multi-threaded architecture, Nginx follows an asynchronous event-based approach for handling multiple client requests.

    The Apache server serves static content using traditional methods and handles dynamic content natively within the web server itself. Nginx, on the other hand, cannot handle dynamic content internally and relies on external processes to do so.

    2. Install Nginx web server

    Update package information with apt update and apt upgrade. Check packages related to nginx with the list option. Install the nginx web server using the nginx installation command.

    • This command displays nginx-related package information.
    sudo apt list nginx*
    nginx ubuntu
    nginx ubuntu
    • Run the command to install nginx.
    sudo apt install nginx
    nginx ubuntu
    nginx ubuntu
    • Check the version of nginx installed.
    sudo nginx -v
    nginx ubuntu
    nginx ubuntu
    • Check the status of the nginx service.
    sudo systemctl status nginx
    nginx ubuntu
    nginx ubuntu

    2. Port settings for external connection

    Even though the web server is installed, it does not mean that you can connect to it right away. The environment where Ubuntu is installed is composed of a virtual server on the host computer, and the Ubuntu server is provided with a firewall service using iptables.

    The first step is to open a port on your ubuntu server. If you need to understand iptables, you can check it out through the following article.

    Ubuntu firewall iptables configuration and management – ​​Thinknote

    1) Allow nginx http port

    The http port uses 80. Open iptables to use TCP port 80 and print out the rules to see if the chain is registered in iptables.

    • -A : Add to chain
    • -p tcp : protocol tcp
    • -m tcp: tcp match, extended match
    • –dport: Port number
    • — j : Jump to target
    • ACCEPT: Allow
    sudo iptables -A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
    sudo iptables -S
    iptables
    iptables

    Save the added rules and reload.

    sudo netfilter-persistent save
    sudo netfilter-persistent reload
    iptables
    iptables

    2) Add VirtualBox port

    You must add a port to VirtualBox to be able to connect from the host computer’s IP or localhost (127.0.0.1). And if you are using a router, you can connect from outside by using the router’s DMZ function or the router’s port forwarding function. This does not cover the router’s DMZ settings.

    If you want to know the detailed procedures of VirtualBox, you can click the link below.

    Ubuntu SSH port settings and connection – Thinknote

    Add forwarding to port 80 as shown in the image below.

    virtualbox 80 port
    virtualbox 80 port

    3. Check Nginx web server connection

    Once the port opening is complete, connect to the nginx web server on the Ubuntu server through the host computer’s Internet browser.

    • Connect to localhost (127.0.0.1)
    nginx
    nginx
    nginx
    nginx
    • Connect to the internal IP of the host computer
    nginx
    nginx
    • Connect to external IP
    nginx
    nginx

    Good article to read together

    • Install Nginx web server (Centos 8)
    • Install and enable Ubuntu firewall iptables
    • Ubuntu firewall iptables setup and management
    • Install PHP 8 (ubuntu)
    • Setting up Nginx + Php8

    Related Reading

    Continue with these related Thinknote English articles in the Server & Infrastructure cluster.

    FAQ

    What is this article about?

    This article is part of Thinknote’s English server and infrastructure archive. It focuses on practical Linux, Ubuntu, web-server, database, SSH, firewall, or hosting operations that readers can adapt to their own environment.

    How should I use this guide?

    Use it as a practical checklist and concept guide. Before applying commands on a live server, verify package names, OS versions, ports, and backup requirements for your own setup.

    Where can I read the original Korean article?

    The original Korean article is available here: Original Korean article.

  • Install PHP 8 (ubuntu)

    Install PHP 8 (ubuntu)

    1. Understanding and features of PHP

    1) Understanding PHP

    The purpose of installing PHP 8 is to use WordPress in conjunction with the Nginx web server. In the future, we will also cover how to use PHP to manipulate some data and insert PHP code, but rather, we will explain it for the purpose of operating WordPress developed with PHP.

    Original Korean article: Install PHP 8 (ubuntu)

    PHP stands for Hypertext Preprocessor and is designed to implement dynamic web pages. You can create the desired web page by processing code written in PHP like an HTML file in the PHP engine. PHP is moving to version 8.x, and after 7.0, PHP code and HTML are written separately as separate files and are increasingly executed through php-fpm (PHP FastCGI Process Manager) rather than a web server.

    Server-side open source software is often implemented in PHP. Representative programs based on PHP include WordPress, MediaWiki, and NextCloud. PHP has strengths in text and HTML processing, so it can apply a variety of things such as URL parsing, form processing, and regular expressions, and supports various databases.

    Various programming languages ​​such as Java and Python are widely used, but continuous development is underway based on the influence of open source.

    2) PHP features

    PHP has four characteristics: simplicity, efficiency, security, flexibility, and familiarity.

    • PHP can perform system functions i.e. create, open, read, write and close files on the system.
    • PHP can collect data from forms, i.e. files, save data to files, send data via email, and return data to the user.
    • Add, delete and modify elements in the database via PHP.
    • Access cookie variables and set cookies.
    • PHP allows you to restrict users from accessing some pages on your website.
    • You can encrypt your data.

    3) Utilization of PHP

    Tasks that would have required multiple Includes to be accessed in Java or C language are built-in functions, so they can be easily implemented with a small amount of code. Current PHP has evolved from a procedural form to a state where ‘object-oriented (class)’ programs can be written.

    • PHP can generate dynamic page content.
    • PHP can create, open, read, write, delete and close files on the server.
    • PHP can collect form data.
    • PHP can send and receive cookies.
    • PHP can add, delete and modify data in the database.
    • You can control user access using PHP.
    • PHP can encrypt data

    2. Install PHP 8

    1) Preparation for PHP 8

    Update and upgrade Ubuntu packages.

    sudo apt update
    sudo apt upgrade
    php 8
    php 8

    2) Check and install PHP 8 package

    You can check items related to PHP with the apt list command. However, because there are so many PHP-related packages, I am hesitant about what to install. In particular, since PHP versions vary, a specific version may be required for the development environment of existing programs.

    The core of the PHP installation is php-fpm. Depending on the PHP version, it exists for each version such as php7.x-fpm, php8.x-fpm, etc. We will cover how to install a specific version in another article.

    Check the core packages of your PHP 8 installation with apt list *fpm. Here, php-fpm is version 8.1 and php-fpm is version 8.1.2. The latest version may be good, but it is also a good idea to avoid the most recent version because compatibility problems may occur.

    sudo apt list *fpm
    php 8
    php 8

    Here we install php.

    sudo apt install php8.1-fpm
    php 8
    php 8
    php 8
    php 8
    php 8
    php 8

    3) Check PHP 8 status

    To check that the installation is complete and operating properly, run the sudo systemctl status php8.1-fpm command. If you previously installed a specific version, you can check it by writing the version in php.

    sudo systemctl status php8.1-fpm
    php 8
    php 8

    The service is running normally. Looking at the output, the service operates as php8.1-fpm.service and the conf file is /etc/php/8.1/fpm/php-fpm.conf.

    4) Additional installation of php 8 package for WordPress

    Some packages may not be needed right now. However, since it doesn’t really matter if you install it in advance, install all the basic packages.

    sudo apt install php8.1-common php8.1-mysql php8.1-xml php8.1-xmlrpc php8.1-curl php8.1-gd php8.1-imagick php8.1-cli php8.1-dev php8.1-imap php8.1-mbstring php8.1-opcache php8.1-redis php8.1-soap php8.1-zip
    php 8
    php 8

    3. Connect Nginx and PHP 8

    Installing the PHP package does not mean that the PHP file will be applied to the web server. Some files need to be modified so that nginx can serve PHP.

    1 file exists and 3 files need to be modified.

    1. The /etc/nginx/nginx.conf file exists.
    2. Check and add fastcig_param in /etc/nginx/fastcgi_params
    3. Add and modify php script in /etc/nginx/sites-available/default setting
    4. default_type in /etc/nginx/nginx.conf

    Fourth, if you do not fix it, there will be a problem where the php file will not run and be downloaded.

    1) Check /etc/nginx/nginx.conf

    If you followed the previous installation and steps, the nginx.conf file exists. If you don’t have it, just copy the following content and create a file. If you copy the contents below to create a file, you can skip step 4.

    Create a file.

    sudo nano /etc/nginx/nginx.conf

    Paste the following code:

    user www-data;
    worker_processes auto;
    pid /run/nginx.pid;
    include /etc/nginx/modules-enabled/*.conf;
    
    events {
            worker_connections 768;
            # multi_accept on;
    }
    
    http {
            ##
            # Basic Settings
            ##
            sendfile on;
            tcp_nopush on;
            types_hash_max_size 2048;
            # server_tokens off;
            # server_names_hash_bucket_size 64;
            # server_name_in_redirect off;
            include /etc/nginx/mime.types;
            #default_type application/octet-stream;
            default_type text/html;
            ##
            # SSL Settings
            ##
            ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE
            ssl_prefer_server_ciphers on;
    
            ##
            # Logging Settings
            ##
            access_log /var/log/nginx/access.log;
            error_log /var/log/nginx/error.log;
    
            ##
            # Gzip Settings
            ##
            gzip on;
            # gzip_vary on;
            # gzip_proxied any;
            # gzip_comp_level 6;
            # gzip_buffers 16 8k;
            # gzip_http_version 1.1;
            # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
    
            ##
            # Virtual Host Configs
            ##
            include /etc/nginx/conf.d/*.conf;
            include /etc/nginx/sites-enabled/*;
    }
    
    #mail {
    #       # See sample authentication script at:
    #       # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
    #
    #       # auth_http localhost/auth.php;
    #       # pop3_capabilities "TOP" "USER";
    #       # imap_capabilities "IMAP4rev1" "UIDPLUS";
    #
    #       server {
    #               listen     localhost:110;
    #               protocol   pop3;
    #               proxy      on;
    #       }
    #
    #       server {
    #               listen     localhost:143;
    #               protocol   imap;
    #               proxy      on;
    #       }
    #}

    2) Check and add fastcig_param in /etc/nginx/fastcgi_params

    Open /etc/nginx/fastcgi_param with an editor and add the following if it does not already exist:

    sudo nano /etc/nginx/fastcgi_params

    Add the following code to the first line:

    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    Article image 8
    Article image 8

    3) Add and modify php script in /etc/nginx/sites-available/default setting.

    Run the default file with an editor and modify the location part as follows. Here, we modify it based on version 8.1. Simply find and change the following part of the existing file:

    # pass PHP scripts to FastCGI server
    
    location ~ \.php$ {
           include snippets/fastcgi-php.conf;
    
           # With php-fpm (or other unix sockets):
           fastcgi_pass unix:/run/php/php8.1-fpm.sock;
    }
    Article image 9
    Article image 9

    Restart both Nginx and PHP.

    sudo systemctl restart nginx
    sudo systemctl restart php8.1-fpm

    4. Run PHP 8 and check

    Create a file to check PHP information. The file is created in the web root.

    sudo nano /var/www/html/info.php

    Copy and paste the following content according to the PHP code rules.

    <?php
    phpinfo();
    ?>

    Check the php information on the website with localhost/info.php or address/info.php.

    Article image 10
    Article image 10

    Please note that in order to install WordPress, you must modify the php.ini file. Executing the php file and modifying the php.ini file will be covered in the WordPress installation article.

    Good article to read together

    • Setting up Nginx + Php8
    • Free HTTPS setup (Let’s Encrypt, Cloudflare)
    • Install memory caching APCu, Redis, Memcached
    • Install Nginx web server (Centos 8)
    • Install Nginx web server (ubuntu)

    Related Reading

    Continue with these related Thinknote English articles in the Server & Infrastructure cluster.

    FAQ

    What is this article about?

    This article is part of Thinknote’s English server and infrastructure archive. It focuses on practical Linux, Ubuntu, web-server, database, SSH, firewall, or hosting operations that readers can adapt to their own environment.

    How should I use this guide?

    Use it as a practical checklist and concept guide. Before applying commands on a live server, verify package names, OS versions, ports, and backup requirements for your own setup.

    Where can I read the original Korean article?

    The original Korean article is available here: Original Korean article.

  • How to Use the R Pipe Operator for Data Analysis Workflows

    How to Use the R Pipe Operator for Data Analysis Workflows

    The pipe operator (%>%) in R allows you to increase both the readability and efficiency of your R programming code at the same time.

    파이프 연산자
    파이프 연산자

    Original Korean article: How to use the R pipe operator %>%: An easy way to read data analysis flows

    The R pipe operator is a grammar that helps you read the multi-step data processing process from top to bottom. The more nested functions you have, the more complex your code becomes, but pipes allow you to organize your analysis flow into a natural order. This article explains the basic structure of %>%, how to read it, and frequently used patterns in data analysis.

    In this article, we will take a detailed look at what these pipe operators are, why they are needed, and how they can be used.

    1. What is the pipe operator %>%?

    The %>% operator, or pipe operator, is mainly used in the dplyr and tidyverse packages. The main purpose of this operator is to clearly pass data or results to the next function.

    This makes your code more modular and makes it clear what's happening at each step.

    # example example
    result <- data %>%
      filter(age > 30) %>%
      select(name, age)

    2. Why should we use the pipe operator %>%?

    1) Improved code readability

    It makes complex data processing processes easier to understand at a glance. Typically, when multiple functions and operations are listed on a single line in R code, reading that code requires considerable effort.

    However, by using the pipe operator, you can clearly distinguish each step and understand the code more intuitively.

    2) Increased maintainability

    Code written using the pipe operator is easy to modify and extend. If you need to add or delete a new operation in a specific step, you only need to modify that part. This makes code easier to maintain.

    3) Intuitive data processing

    Pipe operators represent the flow of data vertically. This helps you understand more intuitively how your data is transformed.

    3. Example of pipe operator usage

    The %>% operator is also called the pipe operator and is mainly used in R, especially in the dplyr package and tidyverse package. The basic role of this operator is to connect the input and output of a function in a clear and readable way.

    The pipe operator receives data, processes it, and passes the result as the first argument to the next function. This makes the code much more readable and provides a clearer view of the data processing flow.

    For example, the following two pieces of code, using dplyr 's filter() and select() functions, accomplish the same thing:

    If you don't use the pipe operator:

    filtered_data <- filter(data, age > 30)
    result <- select(filtered_data, name, age)

    When using the pipe operator:

    result <- data %>%
      filter(age > 30) %>%
      select(name, age)

    In the second example using pipes, you can see at a glance the code starting from data ( data ) and what transformations ( filter , select ) it goes through. In this way, the pipe operator improves the readability of your code and helps you express your logic more clearly.

    1) Pipe operator basic data processing

    First, let's load the dplyr package and do simple data filtering, selection, and sorting.

    # dplyr example example
    library(dplyr)
    
    # example example
    filtered_data <- mtcars %>%
      filter(mpg > 20)
    
    # example example example example
    sorted_data <- mtcars %>%
      select(mpg, cyl) %>%
      arrange(desc(mpg))

    2) Pipe operator complex data processing scenarios

    Even complex data processing can be expressed concisely through the pipe operator.

    The example below shows the process of filtering, grouping, summarizing, and sorting mtcars data all at once.

    result <- mtcars %>%
      filter(mpg > 20) %>%
      group_by(cyl) %>%
      summarise(avg_mpg = mean(mpg)) %>%
      arrange(desc(avg_mpg))

    4. Conclusion

    The pipe operator %>% is a powerful tool for effectively processing data in R programming. You can increase the readability of your code, improve maintainability, and clearly express the logic of data processing.

    So, the use of this operator is almost essential when performing data analysis or data science work in R. Enjoy a more efficient data analysis experience with the %>% operator.

    To download the R program, you can click the download link on the R program's official website (https://www.r-project.org/).

    View all R programs

    Good article to read together

    • Text replacement str_replace, str_replace_all functions
    • str_squish function to remove unnecessary spaces
    • Understanding Tibble and the as_tibble() function
    • unnest_tokens() function
    • Execute PHP and R code in conjunction

    Key Checklist

    • Can the analysis sequence be read from top to bottom?
    • Is piped code clearer than nested functions?
    • Have you confirmed what the input and output data are for each step?
    • Are you creating pipe chains that are longer than necessary?

    Good R statistics articles to read together

    • How to use unnest_tokens function: How to split by words in R text mining
    • Variables and Measurement R Statistics: Understanding independent variables, dependent variables and measurement levels
    • What is research: Summary of research concepts for introduction to R statistics
    • Validity/Reliability R Statistics: Criteria for judging a good measurement tool

    Related Reading

    Continue with these related Thinknote English articles in the Data Analysis cluster.

    FAQ

    What is this article about?

    This article is part of Thinknote’s English R statistics and data-analysis archive. It explains research, measurement, text processing, or tidyverse-style workflow concepts in practical language.

    How should I use this guide?

    Use it as a learning note and starter reference. When applying code, adjust package versions, object names, and dataset structure to your own R environment.

    Where can I read the original Korean article?

    The original Korean article is available here: Original Korean article.

  • Setting up Nginx + Php8

    Setting up Nginx + Php8

    1. Connect Nginx and PHP 8

    Installing the nginx php8 package does not mean that the php file will be applied to the web server. Some files need to be modified so that nginx can serve php8. If your settings are incorrect, php8 will not work properly with nginx. In particular, there is a problem where nothing appears when the php file is downloaded or when phpinfo or php code is run.

    Original Korean article: Setting up Nginx + Php8

    The part we are checking now will help PHP operate properly on the web server through nginx and PHP8 settings.

    1 file exists and 3 files need to be modified.

    1. The /etc/nginx/nginx.conf file exists.
    2. Check and add fastcig_param in /etc/nginx/fastcgi_params
    3. Add and modify php script in /etc/nginx/sites-available/default setting
    4. default_type in /etc/nginx/nginx.conf

    Fourth, if you do not fix it, there will be a problem where the php file will not run and be downloaded.

    1) Check /etc/nginx/nginx.conf

    If you followed the previous installation and steps, the nginx.conf file exists. If you don’t have it, just copy the following content and create a file. If you copy the contents below to create a file, you can skip step 4.

    The user set below may differ depending on the PHP version. user must match the user, group, listen.owner, and listen.group information in sudo nano /etc/php/8.1/fpm/pool.d/www.conf.

    Create a file.

    sudo nano /etc/nginx/nginx.conf

    Paste the following code:

    user www-data;
    worker_processes auto;
    pid /run/nginx.pid;
    include /etc/nginx/modules-enabled/*.conf;
    
    events {
            worker_connections 768;
            # multi_accept on;
    }
    
    http {
            ##
            # Basic Settings
            ##
            sendfile on;
            tcp_nopush on;
            types_hash_max_size 2048;
            # server_tokens off;
            # server_names_hash_bucket_size 64;
            # server_name_in_redirect off;
            include /etc/nginx/mime.types;
            #default_type application/octet-stream;
            default_type text/html;
            ##
            # SSL Settings
            ##
            ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE
            ssl_prefer_server_ciphers on;
    
            ##
            # Logging Settings
            ##
            access_log /var/log/nginx/access.log;
            error_log /var/log/nginx/error.log;
    
            ##
            # Gzip Settings
            ##
            gzip on;
            # gzip_vary on;
            # gzip_proxied any;
            # gzip_comp_level 6;
            # gzip_buffers 16 8k;
            # gzip_http_version 1.1;
            # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
    
            ##
            # Virtual Host Configs
            ##
            include /etc/nginx/conf.d/*.conf;
            include /etc/nginx/sites-enabled/*;
    }
    
    #mail {
    #       # See sample authentication script at:
    #       # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
    #
    #       # auth_http localhost/auth.php;
    #       # pop3_capabilities "TOP" "USER";
    #       # imap_capabilities "IMAP4rev1" "UIDPLUS";
    #
    #       server {
    #               listen     localhost:110;
    #               protocol   pop3;
    #               proxy      on;
    #       }
    #
    #       server {
    #               listen     localhost:143;
    #               protocol   imap;
    #               proxy      on;
    #       }
    #}

    2) Check and add fastcig_param in /etc/nginx/fastcgi_params

    Open /etc/nginx/fastcgi_param with an editor and add the following if it does not already exist:

    sudo nano /etc/nginx/fastcgi_params

    Add the following code to the first line:

    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    Article image 1
    Article image 1

    3) Add and modify php script in /etc/nginx/sites-available/default setting.

    Run the default file with an editor and modify the location part as follows. Here, we modify it based on version 8.1. Simply find and change the following part of the existing file:

    # pass PHP scripts to FastCGI server
    
    location ~ \.php$ {
           include snippets/fastcgi-php.conf;
    
           # With php-fpm (or other unix sockets):
           fastcgi_pass unix:/run/php/php8.1-fpm.sock;
    }
    Article image 2
    Article image 2

    Restart both Nginx and PHP.

    sudo systemctl restart nginx
    sudo systemctl restart php8.1-fpm

    4. Run PHP 8 and check

    Create a file to check PHP information. The file is created in the web root.

    sudo nano /var/www/html/info.php

    Copy and paste the following content according to the PHP code rules.

    <?php
    phpinfo();
    ?>

    Check the php information on the website with localhost/info.php or address/info.php.

    Article image 3
    Article image 3

    This article was written by selecting only the problem-solving part of the PHP8 settings after installing nginx, and is duplicated with the previous article. If you want to know more about installing nginx, click the following link:

    Install Nginx web server (ubuntu) – Thinknote

    If you want to install php8 with Ubuntu’s nginx installed, click the following link. PHP installation is a preparatory step for installing WordPress.

    Install PHP 8 (ubuntu) – Thinknote

    Good article to read together

    • Install PHP 8 (ubuntu)
    • Install memory caching APCu, Redis, Memcached
    • Install Nginx web server (ubuntu)
    • Free HTTPS setup (Let’s Encrypt, Cloudflare)
    • Install Nginx web server (Centos 8)

    Related Reading

    Continue with these related Thinknote English articles in the Server & Infrastructure cluster.

    FAQ

    What is this article about?

    This article is part of Thinknote’s English server and infrastructure archive. It focuses on practical Linux, Ubuntu, web-server, database, SSH, firewall, or hosting operations that readers can adapt to their own environment.

    How should I use this guide?

    Use it as a practical checklist and concept guide. Before applying commands on a live server, verify package names, OS versions, ports, and backup requirements for your own setup.

    Where can I read the original Korean article?

    The original Korean article is available here: Original Korean article.

  • Text replacement str_replace, str_replace_all functions

    Text replacement str_replace, str_replace_all functions

    The text replacement (str_replace, str_replace_all) function is a very useful tool in string processing. The text replacement function is included in the stringr package and replaces one string with another.

    텍스트 교체

    Original Korean article: Text replacement str_replace, str_replace_all functions

    1. Concept of text replacement (str_replace, str_replace_all) function

    1) str_replace()

    The str_replace() function replaces the first occurrence of a specific pattern within a string with another string.

    # stringr example example
    library(stringr)
    
    # example
    str_replace("apple orange apple", "apple", "banana")
    # example: "banana orange apple"

    In the example above, “apple” was replaced with “banana” only on its first occurrence.

    2) str_replace_all()

    On the other hand, the str_replace_all() function replaces every specific pattern within a string with another string.

    # example
    str_replace_all("apple orange apple", "apple", "banana")
    # example: "banana orange banana"

    In the example above, all “apple” words have been replaced with “banana”.

    2. Main usage of str_replace, str_replace_all functions

    Basic usage

    • str_replace(string, pattern, replacement)
    • str_replace_all(string, pattern, replacement)

    string: target string pattern: pattern to find replacement: string to replace

    1) Pattern matching using regular expressions

    You can use regular expressions in the pattern parameter. For example, if you want to remove all numbers, you can do this:

    # str_replace() example example
    str_replace("apple1 orange2", "[0-9]", "")
    # example: "apple orange2"
    
    # str_replace_all() example example
    str_replace_all("apple1 orange2", "[0-9]", "")
    # example: "apple orange"

    2) Replace multiple patterns at once

    The str_replace_all() function can replace multiple patterns at once. In this case, we pass pattern and replacement as named vectors.

    # example example example example
    str_replace_all("apple orange pear", c("apple" = "banana", "orange" = "grape"))
    # example: "banana grape pear"

    3) Replace all characters except Korean, English, and numbers with empty data

    You can use the str_replace_all function to replace all characters except Korean, English, and numbers with empty data. Let's apply this using regular expressions.

    Below is an example using the stringr package.

    # stringr example example
    library(stringr)
    
    # example example
    example_str <- "example! Hello, 1234!!@@"
    
    # example, example, example example example example example example example
    cleaned_str <- str_replace_all(example_str, "[^example-examplea-zA-Z0-9]", "")
    
    # example example
    print(cleaned_str)
    #exampleHello1234

    In the above code, "[^ga-hia-zA-Z0-9]" means all characters except Korean (ga-hi), English (a-zA-Z), and numbers (0-9). You can replace these with an empty string and get the result:

    3. Concluding how to use the text replacement function

    The text replacement (str_replace, str_replace_all) function is a very useful tool when processing text data. Using these functions, you can easily solve complex string processing tasks.

    In particular, when used with regular expressions, you can achieve more powerful string processing capabilities.

    To download the R program, you can click the download link on the R program's official website (https://www.r-project.org/).

    View all R programs

    Good article to read together

    • Install PHP 8 (ubuntu)
    • Setting up Nginx + Php8
    • Install memory caching APCu, Redis, Memcached
    • Install Centos 8
    • Linux user management useradd usermod userdel

    Related Reading

    Continue with these related Thinknote English articles in the Data Analysis cluster.

    FAQ

    What is this article about?

    This article is part of Thinknote’s English R statistics and data-analysis archive. It explains research, measurement, text processing, or tidyverse-style workflow concepts in practical language.

    How should I use this guide?

    Use it as a learning note and starter reference. When applying code, adjust package versions, object names, and dataset structure to your own R environment.

    Where can I read the original Korean article?

    The original Korean article is available here: Original Korean article.

  • str_squish function to remove unnecessary spaces

    str_squish function to remove unnecessary spaces

    To remove unnecessary spaces, use the str_squish function. The str_squish function is included in the stringr package of the R programming language and performs the function of removing leading, trailing, and intervening whitespace from a string. To remove unnecessary spaces, let's check the concept and main uses of the str_squish function.

    불필요한 공백제거

    Original Korean article: str_squish function to remove unnecessary spaces

    1. The concept of str_squish

    str_squish() removes unnecessary spaces at the beginning and end of the target string, and reduces consecutive spaces within the string to a single space. For example, if you have a string called “Hello World”, applying the str_squish() function will convert it to “Hello World”.

    # stringr example example
    library(stringr)
    
    # example
    str_squish("   Hello   World  ")
    # example: "Hello World"

    2. Main usage

    Basic usage

    • str_squish(string)

    string: target string

    1) Apply to vector

    The str_squish function can also be applied to string vectors. In this case, the function is applied to each string element.

    # example
    str_squish(c("   Hello  ", "  World  "))
    # example: "Hello" "World"

    2) Apply to data frame

    The str_squish function with the dplyr package allows you to apply a function to specific columns in a data frame.

    # dplyr example example
    library(dplyr)
    
    # example example example
    df <- data.frame(name = c("  Alice  ", "  Bob  ", "  Carol  "),
                     age = c(30, 40, 50))
    
    # str_squish example
    df <- df %>%
      mutate(name = str_squish(name))
    
    # example example
    print(df)

    3. Conclusion

    The str_squish() function is a very useful tool when squeezing text data. This function simplifies complex string processing tasks. It is often used in data analysis or text mining tasks, so it is a good idea to learn how to use this function.

    To download the R program, you can click the download link on the R program's official website (https://www.r-project.org/).

    View all R programs

    Good article to read together

    • 1. What is research? [R Statistics]
    • Text replacement str_replace, str_replace_all functions
    • Understanding Tibble and the as_tibble() function
    • unnest_tokens() function
    • Execute PHP and R code in conjunction

    Practical Use Cases for str_squish()

    In real text analysis projects, unnecessary spaces often appear when data is copied from web pages, spreadsheets, survey answers, PDF extractions, or manually typed forms. A string may look clean on the screen, but it can contain repeated spaces, tabs, or line-break-like spacing that makes grouping, joining, filtering, or tokenizing less reliable.

    The value of str_squish() is that it solves two problems at once. First, it removes leading and trailing whitespace. Second, it compresses repeated internal whitespace into a single normal space. This makes the function especially useful before comparing labels, cleaning names, standardizing categories, or preparing text for tokenization.

    When to Use It in an R Workflow

    • Before using text as a key for joins or matching.
    • Before counting unique values in a survey or category column.
    • Before tokenizing Korean or English text for text mining.
    • Before exporting cleaned data to a report or dashboard.

    A practical rule is simple: if a text column came from outside your own controlled data pipeline, normalize whitespace early. That small cleaning step can prevent confusing duplicate categories and unexpected mismatches later in the analysis.

    Related Reading

    Continue with these related Thinknote English articles in the Data Analysis cluster.

    FAQ

    What is this article about?

    This article is part of Thinknote’s English R statistics and data-analysis archive. It explains research, measurement, text processing, or tidyverse-style workflow concepts in practical language.

    How should I use this guide?

    Use it as a learning note and starter reference. When applying code, adjust package versions, object names, and dataset structure to your own R environment.

    Where can I read the original Korean article?

    The original Korean article is available here: Original Korean article.

  • Understanding Tibble and the as_tibble() function

    Understanding Tibble and the as_tibble() function

    1. What is Tibble?

    Tibble is one of the data structures for handling data in R and can be seen as a more useful extension of R's data frame (data.frame).

    tibble

    Original Korean article: Understanding Tibble and the as_tibble() function

    Tibble is provided as part of the tidyverse package and is compatible with data frames. Tibble has nice-looking data output, is useful when processing partially large data, and is simpler when dealing with variable types or variable names.

    1) Main features

    • Output: Tibble is highly readable when output to the console. First, you may want to show only 10 rows and not all columns.
    • Column data types: Tibble maintains column data types better. For example, character data remains character type.
    • Partial selection of columns and rows: Tibble is also more reliable when using [[]] or $. For example, requesting a column name that does not exist will return an error.

    2) Creating Tibble

    There are several ways to create a Tibble.

    • Create your own using the tibble() function:
    library(tibble) my_tibble <- tibble(x = 1:5, y = 1, z = x ^ 2 + y)
    • Convert an existing data frame to the as_tibble() function:
    my_data_frame <- data.frame(x = 1:5, y = 1, z = x ^ 2 + y) my_tibble <- as_tibble(my_data_frame)
    • Create it directly using the tibble() function: library(tibble) my_tibble <- tibble(x = 1:5, y = 1, z = x ^ 2 + y)
    • Convert an existing data frame to the as_tibble() function: my_data_frame <- data.frame(x = 1:5, y = 1, z = x ^ 2 + y) my_tibble <- as_tibble(my_data_frame)

    3) Using Tibble

    Tibble works much like a data frame, so it is compatible with most data frame functions.

    # example example
    my_tibble$x
    # example example
    my_tibble[1:2,]
    # dplyr example
    library(dplyr)
    my_tibble %>% filter(x > 2)

    4) Tibble add-on

    Tibble also offers some additional features and options. For example, you can force data types and add metadata for rows and columns.

    Tibble is easier to handle, more readable, and can effectively handle large data sets than traditional data frames.

    tibble is a subclass of data frame (data.frame) used when handling data in R. tibble is part of the tidyverse, making data processing simpler and more efficient in a variety of ways. The as_tibble() function converts a given data object into a tibble object.

    3) Check Tibble data type

    To check the tibble data type, you must install the tibble package.

    install.packages("tibble")

    You can check tibble data with is_tibble. The output value of class(ti_iris) [1] “tbl_df” “tbl” “data.frame” indicates that the ti_iris object has multiple classes. In R, an object can have multiple classes, which reflects the object's inheritance structure.

    1. “tbl_df”: This indicates that ti_iris is a data frame in tibble format. tbl_df is a class defined in the tibble package.
    2. “tbl”: This class is the superclass of tbl_df and represents the basic characteristics of a tbl object. This usually appears together with tbl_df and is defined in the tibble package.
    3. “data.frame”: This indicates that ti_iris is also a regular R data frame by default. data.frame is one of the base classes in R.
    is_tibble(ti_iris)
    TRUE
    class(ti_iris)
    [1] "tbl_df"     "tbl"        "data.frame"

    2. Understanding as_tibble() function

    The as_tibble() function converts various data objects (e.g. data.frame, matrix, etc.) into tibble form. A tibble is similar to a data frame, but has some important differences. For example, tibble allows for cleaner data output and more flexibility in handling variable types.

    The as_tibble() function is used to convert data into tibble format and supports various options. Below is a detailed description of the options:

    1) x

    The first argument x is the data you want to convert. This can take many forms: vectors, lists, data frames, matrices, etc.

    as_tibble(data.frame(x = 1:3, y = 4:6))

    2) .rows

    The .rows option specifies the number or range of rows to load. This allows you to select only some rows from a large dataset.

    as_tibble(iris, .rows = 1:5)

    3) .name_repair

    The .name_repair option specifies how to handle column names. This option can have the following values:

    • “minimal”: No modifications are made.
    • “unique”: Makes column names unique.
    • “universal”: Converts to a valid column name.
    • “check_unique”: Checks if column names are unique, otherwise raises an error.
    as_tibble(data.frame(x = 1, x = 2), .name_repair = "unique")

    4) .col_names (deprecated)

    This option was used to specify column names in previous versions, but is now deprecated. Use .name_repair instead.

    5) … (deprecated)

    This is an option to accept additional arguments and is currently deprecated.

    Example:

    # .name_repairexample example example example example
    as_tibble(data.frame(` ` = 1:3, x = c('a', 'b', 'c')), .name_repair = "universal")
    # .rowsexample example example example example
    as_tibble(mtcars, .rows = 1:5)

    Combining these options allows you to perform a wide variety of data transformation tasks.

    3. Main usage of as_tibble() function

    1) Basic usage

    • as_tibble(x, …)

    x : target data object … : additional optional arguments

    2) Convert data frame to tibble

    # tibble example example
    library(tibble)
    # example example example
    df <- data.frame(name = c("Alice", "Bob", "Carol"),
                     age = c(30, 40, 50))
    # as_tibbleexample example
    df_tibble <- as_tibble(df)
    # example example
    print(df_tibble)

    3) Convert matrix to tibble

    # example example
    mat <- matrix(1:6, nrow = 2)
    # as_tibbleexample example
    mat_tibble <- as_tibble(mat)
    # example example
    print(mat_tibble)

    4) Convert list to tibble

    For lists, each list element becomes a column of tibble.

    # example example
    lst <- list(name = c("Alice", "Bob"), age = c(30, 40))
    # as_tibbleexample example
    lst_tibble <- as_tibble(lst)
    # example example
    print(lst_tibble)

    4. as_tibble() complex example

    1) Overlapping data

    The as_tibble function can also handle nested data structures, such as lists of lists.

    # example example
    nested_list <- list(
      meta = list(name = "sample", version = "1.0"),
      data = list(
        id = 1:3,
        value = c("a", "b", "c")
      )
    )
    # example example tibbleexample example
    nested_tibble <- as_tibble(nested_list)
    print(nested_tibble)

    Here, nested_tibble has two columns, meta and data, and each column is again made up of a list.

    2) Combination of data frame and list

    The as_tibble function is also useful when some columns of the data frame are made up of lists.

    # example example example example
    df_with_list <- data.frame(
      id = 1:3,
      meta = I(list(
        list(name = "Alice", age = 30),
        list(name = "Bob", age = 40),
        list(name = "Carol", age = 50)
      ))
    )
    # as_tibbleexample example
    tibble_with_list <- as_tibble(df_with_list)
    print(tibble_with_list)

    In this way, the as_tibble function can flexibly handle complex data structures along with various options. You can obtain more efficient results by utilizing the various features of this function in complex data analysis or preprocessing tasks.

    To download the R program, you can click the download link on the R program's official website (https://www.r-project.org/).

    Good article to read together

    • Text replacement str_replace, str_replace_all functions
    • str_squish function to remove unnecessary spaces
    • unnest_tokens() function
    • Execute PHP and R code in conjunction
    • Importance and usage of pipe operator %>%

    Related Reading

    Continue with these related Thinknote English articles in the Data Analysis cluster.

    FAQ

    What is this article about?

    This article is part of Thinknote’s English R statistics and data-analysis archive. It explains research, measurement, text processing, or tidyverse-style workflow concepts in practical language.

    How should I use this guide?

    Use it as a learning note and starter reference. When applying code, adjust package versions, object names, and dataset structure to your own R environment.

    Where can I read the original Korean article?

    The original Korean article is available here: Original Korean article.